front-end mastery - Immediately Invoked Function Expressions (IIFE)

Jordan Binskin

2019/11/04

Categories: front-end javascript Tags: javascript functions closures

Immediately Invoked Function Expressions (IIFE’s)

An IIFE ^ is a way in JavaScript to define a function and immediately call it after it has been parsed. When defining an immediately invoked function declaration you are able to omit a name for function - making it an anonymous function (this is similar to what you may be used to doing when passing a function as an argument to another function).

To achieve writing an anonymous IIFE see the code block example below, it is imperative that the function is wrapped in a pair of parentheses. Otherwise the parser will read the function declaration and the call as two separate things.


(function() {
  // do something
  var closureBinding = 10;
})();

console.log(closureBinding);
// closureBinding is not defined;

// anonymous IIFE can also be written as:
(function() {

}()); // the function call is now placed inside the enclosing parentheses.

Other than some other small nuance, they aren’t that special in themselves. They can also be named. There power comes in the way they can be used. There is a number of use-cases I see other developers use IIFE.