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

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 add () after the function declaration, the parser does not treat it as a call on the function. Instead, the trailing () is parsed as a separate grouping operator, and because it contains no expression, it throws a SyntaxError.

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 wrap the entire invocation (function and call) in a single pair of parentheses:

(function foo() {})();

Both of these syntaxes are valid and will correctly create an IIFE. Other ways to force the function into an expression context include prefixing it with a unary operator, such as !function foo() {}(); or void function foo() {}();.

Further reading

Edit on GitHub