dev4web
9/2/2016 - 4:09 PM

Assuming you're still using ES5, here's a quick maintenance tip regarding immediately invoked anonymous functions that have a return value t

Assuming you're still using ES5, here's a quick maintenance tip regarding immediately invoked anonymous functions that have a return value that you assign to a variable.

Here's some example code:

var myVar = function() {
  // function body goes here...
  return {
    value: "something"
  }
}();

This is fine but the minor problem that occurs here with regards to maintaining this code is that, at a quick glance, it looks like a typical anonymous function assigned to a variable. But it's not just an anonymous function; it's also an immediately invoked one, as shown by the parentheses at the end.

To improve the readability of the code and make it immediately clear that this function is immediately invoked, you can do the following:

var myVar = (function() {
  // function body goes here...
  return {
    value: "something"
  }
}());

The change is subtle but it's significant for someone scanning the code later and trying to figure out what's going on. You can see I've added an extra set of parentheses around the anonymous function, which serves to visually differentiate this from just a standard anonymous function assigned to a variable. This doesn't change the way the code works, but only adds a few bytes.

I should mention, of course, that with later versions of ECMAScript, you might not need to do this. Usually functions are enclosed in this way to prevent variables from leaking globally, but in ES6+ we can use let and const to ensure variables maintain block scope. Wes Bos discusses that a little bit in this post and you can also read a little bit about IIFEs with arrow functions in this post by Jack Tarantino.