DEV Community

Cover image for IIFE - Immediately Invoked Function Expression - JavaScript
umerjaved178
umerjaved178

Posted on

IIFE - Immediately Invoked Function Expression - JavaScript

Topics covered:

  1. Introduction
  2. Why do we use IIFE
  3. Alternative in ES6+

Introduction

It is a function expression that runs as soon as we define it.

(function(){
  console.log("My favorite hero is Captain America")
})()
Enter fullscreen mode Exit fullscreen mode

The first parathesis make it an expression and last parathesis immediately invokes/calls it.

In short, it runs right away

Why do we use IIFE

Most commonly use of IIFE is to avoid declaring variables in global scope

Let's see how

var num = 20;
{
  var num = 10;
  console.log(num);
}
console.log(num);

// console
// 10
// 10
Enter fullscreen mode Exit fullscreen mode

As javascript has function level scope, let's solve this problem by taking advantage of that

var num = 20
(function consoleNum() {
  var num = 10;
  console.log(num);
})();

console.log(num);
// console
// 10
// 20
Enter fullscreen mode Exit fullscreen mode

Alternative in ES6+

In JavaScript ES6+, we can use the powers of let & const to replace IIFE as let & const has block level scope, so we don't pollute global name space.

let num = 20;
{
  let num = 10;
  console.log(num);
}

console.log(num);
// console
// 10
// 20
Enter fullscreen mode Exit fullscreen mode

This is much cleaner and readable.

Top comments (0)