Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
community creator

What is immediately invoked function expression in Javascript?

Emilie

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

As the name says, this shot is what happens when a function is invoked immediately, even without the instantiation, like below:

// IIFE
(function(){
const sayHello = 'Hello';
console.log(sayHello);
})();

Did you notice the difference between the two functions?

It was the brackets(parentheses)!

IIFE is instantiated by a set of brackets and invoked by another set of brackets next to it in order to run the function immediately.

However, there is another way you can implement an IIFE (shown below). This way was suggested by Douglas Crockford as a more legible choice than the first way. Both of them work in the same manner; so, it’s up to your preference.

(function(greeting){
console.log(greeting);
}('hey'))

Now that you know what IIFE is, let’s talk about the benefits of using it?

No global variable pollution

Do you remember the closure technique? Well, IIFE is another way to take advantage of it. Since it is impossible to access the inner functions and data of IIFE, developers can prevent global variable pollution.

const language = 'JavaScript';
(function learningLanguage(param){
return `I am learning ${param}.`;
})(language)
// returns 'I am learning JavaScript.'

Since the functions are encapsulated with the same global variable language within each file, in terms of parsing, we won’t have any issue with overwriting.

I Hope you enjoyed the IIFE – thank you for reading!

RELATED TAGS

javascript
community creator

CONTRIBUTOR

Emilie
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring