Immediately Invoked Function Expression (IIFE)

Immediately Invoked Function Expression (IIFE) is a JavaScript function used to ignore the variable hoisting from inside the code block. An IIFE is a function that runs when we define it. The Immediately Invoked Function Expression allows us to access the method publicly; while it is managing the privacy for variables declared inside a function. The IIEF is also named as Self-Executing Anonymous Functions.

The Immediately Invoked Function Expression includes the following two parts-

  • It is enclosed with a Grouping Operator ().
  • It is used to interpret functions directly by the JavaScript engine.

Syntax

Example

Here, we have tried to elaborate the concept of IIFE with the help of following example.

Output

After the execution of the code, we will get the following output.

Immediately Invoked Function Expression

Function conversion into IIFEs

Some steps are given below that helps us to convert the function into Immediately Invoked Function Expression-

Step 1: First, we take a regular function definition.

Step 2: Then, we bind that definition with the parentheses to create the function expression.

Step 3: In the final step, we associate the expression with the parentheses ({}) and a semicolon (:) as the sign of ending of the statement.

We will try to understand it with the help of the following example-

Example

Output

After the execution of the above code, we will get the following output.

Immediately Invoked Function Expression

Some important points about IIFE

Example

Output

After the compilation of the code, we will get the following output.

Immediately Invoked Function Expression

Pin It on Pinterest

Share This