Select Page

What is an Immediately-Invoked Function Expression or IIFE?

An Immediately-Invoked Function Expression or IIFE, is an anonymous function expression that is invoked immediately.

So what is the deal with all these parentheses?

The first set of parentheses or “Grouping Operator” will return the contents as an Expression.

Consider the following…

Since the Expression inside the parentheses in the IIFE happens to be a function, the entire function is returned.

The second set of parentheses executes the returned function.

Why does this all matter?

In JavaScript, there are 2 types of functions, named functions and function expressions.

Currently both the function foo and the variable bar are in the window scope commonly referred to as the global scope. This enables them to be called at any time and they are publicly available which leads us back to the IIFE. When we create an IIFE, everything encapsulated within the “Group Operator” gets it’s own private scope.

Now when we try to call the function foo in the global scope, we get a Uncaught ReferenceError because foo isn’t in the global scope anymore and is now in it’s own private scope.