DEV Community

Cover image for What is IIFE in JavaScript?
Rahul
Rahul

Posted on

What is IIFE in JavaScript?

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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📚

Get weekly newsletter of amazing articles I posted this week and some offers or announcement. Subscribe from Here

Top comments (3)

Collapse
 
ajay056 profile image
ak@developer

In the function call the output is supposed to be Hello right

Collapse
 
_genjudev profile image
Larson

yes.

Collapse
 
blindfish3 profile image
Ben Calder

It's probably worth mentioning that IIFE is now largely redundant. If working at a scale where multiple people are working on the same codebase you'd typically be working with modules; which are a more elegant solution to the scoping issues IIFE solved.