Creating maintainable JavaScript code is important if want to keep using the code.

In this article, we’ll look at the basics of creating maintainable JavaScript code by looking at variables and functions.

Function Invocation

We should wrap our immediate function invocations with parentheses so that we can tell them apart from function declarations.

For instance, we should write:

const doSomething = (function() {
  //...
  return {
    message: "hello"
  }
})();

We surround the functions with parentheses so that we know we’re calling it.

Strict Mode

ES5 introduced strict mode, which changes how JavaScript is executed and parsed to reduce errors.

To enable strict mode, we add 'use strict' above the code we want to enable strict mode on.

It’s a common recommendation to avoid placing 'use strict' in the global scope.

This is because if we’re concatenating multiple files into one, then we enable strict mode in all of them.

There’s a good chance that we’ll have errors in our old code if we have strict mode on all the code.

So before we fix all the code to follow strict mode, we should enable strict mode partially.

For instance, instead of writing:

"use strict";

function doSomething() {
  // ...
}

We should write:

function doSomething() {
  "use strict";
  // ...
}

If we want to enable strict mode on multiple functions, we should write:

(function() {
  "use strict";

  function doSomething() {
    // ...
  }
  function doMoreWork() {
    // ...
  }
})();

This is good since we keep strict mode within the function.

New code should always have strict mode on.

It corrects many mistakes like accidentally assigning to built-in global variables and other things.

Modules always have strict mode by default, so we always have to follow it.

#web-development #javascript #technology #software-development #programming

Maintainable JavaScript — Function Invocation and Equality
1.10 GEEK