JavaScript Immediately invoked function expressions (IIFEs)

JavaScript Immediately invoked function expressions (IIFEs)

In Javascript, Functions are first-class Objects, in simple words, functions can be passed as an argument (callback) or can be returned from another function.

Function Declaration and Function Expression:

Function Declaration:
We can declare a function using the ‘function’ keyword followed by the function name, parameters (if any), and the function body enclosed in curly braces {}.

Example 1:

Function Declaration

Function Expression:
Function expressions involve defining a function as part of an expression.

They can be named or anonymous and are often used when functions are assigned to variables or passed as arguments to other functions.

  1. Named Function Expression -

Named Function Expression

2. Anonymous Function Expression -

Anonymous Function Expression

Now Let’s Come to “Immediately Invoked Function Expression” (IIFE).

Immediately Invoked Function Expression

An Immediately Invoked Function Expression (IIFE), pronounced as “iffy,” refers to a function that is executed right after it’s declared.

Syntax :

Immediately Invoked Function Expression

The above example will print the message as soon as it executes the code.

Named vs Anonymous IIFE:

IIFE functions are also declared the same way, we declare the normal Javascript functions.

Example of Named IIFE:

Named IIFE

Example of Anonymous IIFE:

Anonymous IIFE

You can also use the Arrow function variation:

Arrow function

NOTE: Code before the IIFE function should be terminated with a semicolon; otherwise it will throw an error.

IIFE function without Semicolon before

Private Scope and Closure:

Immediately invoked function expressions (IIFEs) can also used to create and access private variables. Such variables are valuable when safeguarding against unintended alterations or adjustments to crucial values.

Closures:
Closure is the ability of a function to use variables or other information outside its local scope/ lexical scope.

Example 1:

Closure

What do you think, what will be the output? Guess and Comment

Let’s Discuss the code execution first!!!

1. Immediately Invoked: The function is immediately invoked by appending () after the function definition:

2. Inner Function Creation: Another function is defined inside this function. This inner function has access to the count variable due to JavaScript closures.

3. Execution: The outer function is executed immediately, initializing count to 0, and returning the inner function.

4. Result: The outer function is called only once and serves as a wrapper for the inner function. The inner function is returned and executed later if assigned to a variable. This pattern is often used to create private variables or encapsulate code.

Example 2:

IIFE with Closure

Now, Can You guess the Output??

In the above example, we store the IIFE function in a variable myCount.
Now the IIFE function will execute as soon as it assigns memory to myCount variable,
Execution: The outer function is executed immediately, initializing count to 0, and returning the inner function. The inner function will not be executed until myCount() is called.

This inner function has access to the count variable due to JavaScript closures.

So, the above code will be reduced to

Now, the count will be printed as soon as myCount() is called.You can observe that even after the execution of the outer function, it still holds the value of count variable because of closure.

This pattern is often used to create private variables or encapsulate code.

Advantages of using IIFE:

  1. IIFE can be used to Perform asynchronous operations.

2. Avoid conflict between the variables of libraries and programs.

3. It runs once and only once.

Let’s see some use cases of IIFE:

IIFE in Asynchronous Functions:

Let’s take an example with setTimeout to understand the use case better.

Without IIFE in Asynchronous Functions

Guess The Output??

OUTPUT:
Current Value of i is 5
Current Value of i is 5
Current Value of i is 5
Current Value of i is 5
Current Value of i is 5

This output might seem counterintuitive at first, but it occurs due to the way JavaScript handles closures and asynchronous behavior.

Here’s what happens:

  • The for loop runs from 0 to 4, incrementing i at each iteration.

  • Inside the loop, setTimeout is called for each iteration. setTimeout schedules the execution of the inner function after a specified delay.

  • The inner function is immediately invoked with i as an argument. However, since i is declared using var, it is function-scoped rather than block-scoped. This means that there’s only one i variable for the entire loop, and its value gets updated with each iteration.

  • When the inner function executes, it captures the reference to the i variable from its outer scope, which is the for loop. At the time of execution, the loop has already been completed and i have the final value of 5.

  • Therefore, when the inner functions execute after the delays, they all log the current value of i, which is 5.

To resolve the issue and ensure that each inner function logs the correct value of i at the time of its creation, you can utilize block-scoped variables introduced with let or another way is to create a separate closure for each iteration of the loop by using an Immediately Invoked Function Expression (IIFE) inside the loop.

Using Immediately Invoked Function Expression:

Using Immediately Invoked Function Expression

In this approach:

  • Inside the for loop, we immediately invoke a function (IIFE) passing the current value of i as an argument index.

  • This creates a separate closure for each iteration of the loop, capturing the value of the index specific to that iteration.

  • Inside the IIFE, we have the setTimeout function that logs the correct value of the index for each iteration after the specified delay.

NOTE: we can create IIFE inside the setTimeout function also, let's take it as well

That’s all from my side.

Wait!!! What makes the man Perfect?

Practice!!! Practice!!! Practice!!!

So, let’s have a Quiz, guess, and Comment your answer, without any Cheating.

Quiz 1.) What’s the Output?

Guess the Output

Quiz 2.) What’s the Output?

Guess the Output

That’s all for this Article, Let’s meet in another Article with some great Knowledge.

If you reach till here,Let’s connect:
LinkedIn
X/Twitter
Github