liveBook · Manning

Immediately invoked function expression

As explained in Secrets of the JavaScript Ninja, Third Edition

An immediately invoked function expression is a function expression that is invoked immediately after it is created.

An immediately invoked function expression (IIFE) is a function expression called as soon as it is created. Parentheses around the function expression make its role clear to the JavaScript parser. section 5.1.1

Listing 5.2 Function declarations and function expressions
function myFunctionDeclaration(){  #A
  function innerFunction() {}              #B
}
 
const myFunc = function(){};  #C
myFunc(function(){              #D
  return function(){};  #E
});
 
(function namedFunctionExpression () {   #F
})();                                    #F
 
+function(){}();      #G
-function(){}();      #G
!function(){}();      #G
~function(){}();      #G

Compare a parenthesized IIFE with alternatives that use unary operators before the function expression. section 5.1.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines the call pattern and explains grouping parentheses as syntax that distinguishes expressions from declarations.
Examples
Shows a parenthesized named function expression called immediately and alternatives prefixed with unary operators.
What you can do after
Build an IIFE by placing a function expression before call parentheses or using a unary operator to make it an expression.
How it connects
Connects function expressions with function calls and contrasts them with function declarations.

Also explained in

Compare how 4 books explain immediately invoked function expression →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.