Link to main pageMain page 🏡

IIFE (Immediately Invoked Function Expression) in JavaScript

In 3 minutes
Posted on 2020-05-24
3 mins read

JS expressions like this have always been very confusing for me:

!function() {
    console.log('hi')
}();

// > hi

Recently I came across the IIFE conception. Immediately Invoked Function Expression is JavaScript function, which runs immediately after the declaration.

This kind of expressions are also known as Self-Executing Anonymous Function:

(function () {
    statements
})();

// or

(function () {
    statements
}());

IIFE contains of two parts:

  • The anonymous function with lexical scope enclosed within the Grouping Operator (). This keeps inner variables within the IIFE idiom and prevents polluting the global scope.
  • The second part creates the immediately invoked function expression () which signals JavaScript to directly interpret this.

You can call IIFE with parameters:

((msg) => console.log(msg))('How was your day?');

// > How was your day?

When function declaration is enclosed in brackets, JS interprets it as a function expression.

By the way, in order to make the function expression you can use any unary operator +,-, !, ~:

// Yes, it looks weird 🤔

-function() {console.log('hi')}();

// > hi

// or even
void function() {console.log('hi')}();

// > hi

You can't use arrow functions with unary operators