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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.