Topics covered:
- Introduction
- Why do we use IIFE
- 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")
})()
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
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
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
This is much cleaner and readable.
Top comments (0)