What is an IIFE in JavaScript?

Shahrooz Me

Hi, I'm Shahrooz, a front-end developer. I'm the author of this blog, nice to meet you!

→ Follow me on Twitter!

TL;DR

IIFE or Immediately Invoked Function Expression is a way to execute functions immediately, as soon as they are created. Using IIFEs can protect the scope of your function and the variables within it.

Before we can learn IIFE we need to understand the function declaration and function expression.

Function Declaration

Function declaration is a typical function that perform actions.

function doSomething() {
  // do something...
}

Function Expression

Function expression is another way to define a function that produces a value.

const doSomethingLater = function() {
  // do something later...
}

Immediately Invoked Function Expression

An IIFE looks like a typical function declaration except it’s wrapped in paranthesis and has a second set of paranthesis at the end.

(function () {
  // do something immediately
})()

IIFEs can be defined with arrow functions as well:

(() => {
  // do something immediately
})()