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. A declaration does not produce an expression for a following call operator to invoke, although its binding is initialized during scope setup and can be called by name.

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

An arrow function can also be used when the IIFE does not need its own name or dynamic this binding:

(() => {})();

Both forms create and immediately invoke a function expression. Other ways to force a traditional function into an expression context include prefixing it with a unary operator, such as !function foo() {}(); or void function foo() {}();.

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise
Check your understanding Exercise

Why does the first snippet invoke successfully without grouping parentheses around the function, while the second is a syntax error?

const result = function answer() { return 42; }();
function answer() { return 42; }();