What is IIFE in JavaScript?

What is IIFE in JavaScript?

·

3 min read


Privacy is important and IIFEs can be useful to achieve it. While reading many posts about JavaScript interviews I came towards this term so I thought of learning and writing about it.


What is it?

Immediately Invoked Function Expression (IIFE) are basically the functions that are invoked after completion of the definition. There times when multiple people are working on a project in a team. Suppose you create a function in one file and your team member creates function with the same name in another file. Now when both the files are included in the same web page, there is a very likely possibility of your global scope getting polluted due to the same name of the functions. This is where IIFE can help you out.


How it helps?

Example:

function greet() {
    console.log('Hello'); 
}

function greet() {
    console.log('Hey'); 
}

greet() // Hey

Here, we have two functions with the same name. This can be a problem as the second one will override first one and we will get "Hey" on our console. Now how to overcome this? Well, this is where you use IIFE.

IIFE

Example:

function greet() {
    console.log('Hello'); 
}

(function greet() {
    console.log('Hey'); 
})(); // "Hey"

greet() // Hey

Here, we make the second function an IIFE by enclosing it in parentheses. This is the syntax for an IIFE. Now how it solves our issue is by giving the function its own scope and this prevents it from the messing with our global scope.

This function is invoked as soon as its declaration is complete. And as result we see "Hey" and "Hello" both on our screen. Because now out greet() refers to the globally created greet function.


😳Thanks For Reading | Happy Coding📚

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!