Immediately Invoked Function Expression aka IIFE

Immediately Invoked Function Expression aka IIFE

Hello JavaScript Lovers!
Have you heard of this design pattern before?
Whether you have or not, it is a very useful one when you work with JS. Before we jump into Immediately Invoked Function Expression(hereafter IIFE), check my other blog about lexical scoping and closure if you haven't solidified those techniques.

As the name says, it is a function invoked immediately even without the instantiation just like below.

// IIFE
(function(){
    const sayHello = 'Hello';
    return sayHello;
})();
// returns 'Hello'
// Invocation
greeting();
//return 'Hiya'

function greeting(){
    return 'Hiya!'
}

Do you notice the difference between the two functions?
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. There is another way you can implement an IIFE like down below which was suggested by Douglas Crockford as a more legible choice than the other one. It's up to your preference. Both of them work in the same manner.

(function(greeting){
    return greeting;
}('hey'))

// returns 'hey'

Now you know what IIFE is, shall we talk about the benefits of using it?

NO Global Variable Pollution

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

// file1.js
const language = 'JavaScript';

(function learningLanguage(param){
    return `I am learning ${param}.`;
})(language)
// returns 'I am learning JavaScript.'
// file2.js
const language = "Python";
(function learningAnotherLanguage(param) {
      learningNewLanguage(param);
      whatLanguage();

  function learningNewLanguage(param) {
    console.log(`Learning ${param} is fun!.`);
  }

  function whatLanguage() {
    console.log(`${param} is a server-side language.`);
  }
})(language);

// 'Learning Python is fun!.'
// 'Python is a general purpose language.'

As the functions are encapsulated, the same global variable language within each file, in order of parsing, won't have any issue overwritten.

Private Scoping & Efficient memory usage

You'll never know the total number of clicks

As I created the private scope from implementing the closure technique, the count variable cannot be accessed from the outer scope. Furthermore, the inner variable count retains its value as it keeps incremented if the button is clicked, but, the memory doesn't take up any space as it is already invoked and its stack is cleaned.

Hope you enjoyed the IIFE and check out my other JS blogs below. Thank you for reading!