Immediately Invoked Function Expressions (IIFE)

suggest change

Sometimes you don’t want to have your function accessible/stored as a variable. You can create an Immediately Invoked Function Expression (IIFE for short). These are essentially self-executing anonymous functions. They have access to the surrounding scope, but the function itself and any internal variables will be inaccessible from outside. An important thing to note about IIFE is that even if you name your function, IIFE are not hoisted like standard functions are and cannot be called by the function name they are declared with.

(function() {
   alert("I've run - but can't be run again because I'm immediately invoked at runtime,
          leaving behind only the result I generate");
}());

This is another way to write IIFE. Notice that the closing parenthesis before the semicolon was moved and placed right after the closing curly bracket:

(function() {
   alert("This is IIFE too.");
})();

You can easily pass parameters into an IIFE:

(function(message) {
   alert(message);
}("Hello World!"));

Additionally, you can return values to the surrounding scope:

var example = (function() {
   return 42;
}());
console.log(example); // => 42

If required it is possible to name an IIFE. While less often seen, this pattern has several advantages, such as providing a reference which can be used for a recursion and can make debugging simpler as the name is included in the callstack.

(function namedIIFE() { 
    throw error; // We can now see the error thrown in 'namedIIFE()'
}());

While wrapping a function in parenthesis is the most common way to denote to the Javascript parser to expect an expression, in places where an expression is already expected, the notation can be made more concise:

var a = function() { return 42 }();
console.log(a)  // => 42

Arrow version of immediately invoked function:

(() => console.log("Hello!"))(); // => Hello!

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents