Immediate invocation

There's yet another common usage of functions, usually seen in popular libraries and frameworks, that lets you bring some modularity advantages from other languages into JavaScript (even the older versions!). The usual way of writing this is something like the following:

(function() {  // do something...})();
Another equivalent style is (function(){ ... }())—note the different placement of the parentheses for the function call. Both styles have their fans; pick whichever suits you, but just follow it consistently.

You can also have the same style, but pass some arguments to the function that will be used as the initial values for its parameters:

(function(a, b) {  // do something, using the  // received arguments for a ...

Get Mastering JavaScript Functional Programming - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.