What is IIFE? — Javascript

I was looking up some Javascript interview questions to prepare for and saw the classic closure question and the fizz buzz loop, but then IIFE showed up and I didn’t know how to answer that.

IIFE stand for Immediately Invoked Function Expression. You might have seen it before, but I never really dived into why IIFE is used.

( function invokeNow () {} ) ();

So to understand IIFE, we need to understand what's the difference between a statement and an expression.

function invokeStatement () {}; // statement

var invokeExpression = function () {}; // expression

An expression creates a single value, where a statement is an action. Trying to invoke:

function invokeStatement () {} (); // will throw error

Because Javascript reads the above line as:

function invokeStatement () {};


Which doesn’t make sense at all.

Therefore IIFE is written with parathesis around the statement, so it is treated as an expression that can be invoked.

Okay, but why do I want to use IIFE? The answer I found: control variable scope. We want to contain that function in its own scope.

(function invokeNow () {}) ();

console.log(invokeNow); // will log: invokeNow is not defined.

Sounds familiar? Yep, it’s a closure. Therefore, IIFE can encapsulate variables for use with event handlers.

document.querySelector(‘div’).addEventListener(‘click’, ( function () { var val = 5, name = ‘dude’; return function(){ console.log( val, name ); }})())

It allows you to have global variables for a particular function without making them truly global and polluting the global space. (Thank you to my instructor Dan Paschal for above information).

Control variable scope is great for future coding, avoids collision of same variable names, and encapsulating variables. Since the variable, invokeNow, is IIFE, it has a limited scope, independency, and won’t be hoisted like a normal statement. Therefore, other people and future you will be free to name variables with reduced collisions.