What is immediately invoked function expression in Javascript?

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!

Free Resources

Attributions:
  1. undefined by undefined
Copyright ©2025 Educative, Inc. All rights reserved