Please note, this is a STATIC archive of website www.javatpoint.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
Javatpoint Logo
Javatpoint Logo

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





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA