Quiz

Explain why the following doesn't work as an IIFE: `function foo(){}();`. What needs to be changed to properly make it an IIFE?

Topics
JavaScript
Edit on GitHub

TL;DR

The code function foo(){}(); doesn't work as an Immediately Invoked Function Expression (IIFE) because the JavaScript parser treats function foo(){} as a function declaration, not an expression. To make it an IIFE, you need to wrap the function in parentheses to turn it into a function expression: (function foo(){})();.


Why the code doesn't work as an IIFE

Function declaration vs. function expression

In JavaScript, a function declaration and a function expression are treated differently by the parser. The code function foo(){} is interpreted as a function declaration. Function declarations are not immediately invoked; they are hoisted to the top of their scope and can be called later in the code.

Syntax error

When you try to immediately invoke a function declaration by adding (); at the end, it results in a syntax error because the parser expects a function expression to be invoked immediately, not a declaration.

How to properly make it an IIFE

Wrapping in parentheses

To convert the function declaration into a function expression, you need to wrap the function declaration in parentheses. This tells the JavaScript parser to treat it as an expression. Here is the corrected code:

(function foo(){})();

Alternative syntax

You can also use an alternative syntax by placing the parentheses around the original line:

(function foo(){}());

Both of these syntaxes are valid and will correctly create an IIFE.

Further reading

Edit on GitHub