JavaScript IIFE

In JavaScript IIFE (Immediately Invoked Function Expression) is a way to execute function immediately as soon as it’s defined.
Usually when we create a function, we have to call them ignorer to use them. However, IIFE runs as soon as it’s created.

Why Use IIFE

  • Instead of creating things as global objects, we could take benefit of IIFE.
  • We could use IIFE to declare variable that we need to use in our programme.
  • IIFE don’t pollute the global JavaScript object.
  • IIFE are useful for handling events like onClick()

Syntax of IIFE

  • IIFE are created using two brackets ()()
  • The first bracket will define the function and the second bracket is for executing the function.
  • The function doesn’t have a name and it’s inside the first brackets so it can be treated as an expression. Function declaration requires function to have a name. However, if function is used as an expression it doesn’t need a name.
  • Below are steps for creating an IIFE
    • Step 1: write 2 sets of brackets. The first set is an expression, the second one invokes the expression
      (expression)(invocation of the expression)
    • Step 2: the expression is a function with no name (anonymous function) that contains all your logic(function() {})()
    • Step 3: place all your code inside the anonymous function. Below is a complete IIFE creation syntax.
      (function() {
      all the code in here

There are many other ways of creating IIFE.

Example of IIFE

  • In above example, we want to show a message when a button is clicked.
  • First we have created an HTML with a button with ID fooBtn. Then we have taken that button in JavaScript using document.getElementById(‘fooBtn’) and saved it in a constant named fooBtnCon
  • Inside IIFE we have created a function named iAmClicked and saved our alert message in this function
  • We have added an event listener to fooBtnCon like this addEventListener(‘click’, iAmClicked);. This event listener want to know what even it should listened to (click) and what function it should run (iAmClicked).

IIFE vs function vs Anonymous function :

We know that functions are a reusable piece of code. Once we have declared a function and given it a name, we can use it by calling its name. In below example we are creating a simple function

  • Function without a name are called anonymous function or function literals. Anonymous functions can be used as an event handlers and listeners.
  • Anonymous function can be used as an expression – we can assign the function to a variable
  • In example below, we have recreated the above add function as an expression. We have saved the complete function into a variable named addNum and the called addNum like a normal function.

  • IIFE is also a function but it doesn’t have a name. IIFE is called as soon it is declared by using the second brackets. In example below, we have recreated the above add function as IIFE