Home » ES6 Immediately Invoked Function Expression

ES6 Immediately Invoked Function Expression

by Online Tutorials Library

Immediately Invoked Function Expression (IIFE)

It is a JavaScript function that runs as soon as it defined. An IIFE (Immediately Invoked Function Expression) can be used for avoiding the variable hoisting from within the blocks. It allows the public access to methods while retaining the privacy for variables defined in the function.

IIFE is a design pattern that is also known as the Self-Executing Anonymous Function. It contains two major parts:

  • The first part is the anonymous function having a lexical scope, which is enclosed within the Grouping operator ().
  • The second part creates the IIFE by which the JavaScript engine will interpret the function directly.

Syntax

Let us try to understand the concept of IIFE by using the following example.

Example

Output

Hello World  

Conversion of Functions into IIFEs

We can convert the regular functions into IIFE by using the following steps:

  • Suppose any regular function definition.
  • Wrap that definition within the pair of parentheses, which will create the function expression.
  • At last, we have to add a pair of parentheses and a semicolon for marking the end of the statement.

Let’s see the illustration for the same in the following example:

Example

Output

Regular function  Immediately Invoked Function Expression  

Key points about IIFEs

  • Immediately invoked function expressions (IIFEs) have their scope. The variables declared in the function expression will not be available outside the function.
  • Like other functions, IIFEs can also be anonymous or named.
  • IIFEs can also be parameterized. For example,

Example

Output

100  200  300  

Next TopicES6 Arrays

You may also like