Javascript Syntax for Immediately-Invoked Function Expression (IIFE)
There are two common Javascript syntax for Immediately-Invoked Function Expression (also known as IIFE and pronounced iffy). The two syntax are …
(function() { /* code */ }());
and …
(function() { /* code */ })();
They both work and boils down to personal preference. But Javascript guru Douglas Crockford seems to prefer using the first IIFE syntax.
First IIFE syntax
First IIFE syntax goes like this. Consider an anonymous function definition that defines a variable name and outputs it to the browser console…
If you run this, Javascript complains with …
“Uncaught SyntaxError: Unexpected token (“
This is fixed by wrapping the whole thing withing parenthesis…
Now no syntax error, but the function will not run. To make any Javascript function run, we invoke it with suffixing the function name with open and close parenthesis. Since our function has no name, we put the invoking parenthesis after the function definition like this …
And then end the whole thing with a semicolon.
So that expression defines a function and immediately invokes it.
Second IIFE syntax
The second syntax for an Immediately-Invoked Function Expression (IIFE) looks like this …
This just runs two line of Javascript to display “Hi World” to the browser console.
The name variable is defined within the Immediately-Invoked Function Expression. But it is not available outside the function.
That means anything defined withing the Immediately-Invoked Function Expression stays within the Immediately-Invoked Function Expression. This is Javascript closure and help prevent polluting the global namespace with too many global variables.
How to Remember the IIFE syntax
The syntax looks funny and is difficult to remember at first glance. But if you break it apart piece by piece, it will be easier to understand.
Start with a Javascript anonymous function …
This function has no name and it doesn’t need one.
No harm in wrapping it within parenthesis, which are just grouping symbols…
A function is involved by suffix of two parenthesis. For example to invoke the function foo(), we would write …
foo();
So to invoke our anonymous function, we just suffix it with two parenthesis like this …
Now our anonymous function will be automatically invoke as so as the browser loads it. That’s it. That’s the syntax.
Like any function, you can pass things into it via its parameters at the time of invokation. Here we pass the object jQuery to the calling of the function.
But for this to work, we have to define our anonymous function with a parameter name (in this can our parameter name is $) …
And we can use the parameter value (in our case $) inside our immediately invoked anonymous function.
The reason we named our parameter $ is that jQuery typically name its jQuery object as $.