About me

I am a full stack .net developer with 5 years of experience in front-end and back-end technologies like HTML, CSS, Jquery, Angular, Typescript, Bootstrap, C#, MSSQL and Mongodb. I have done Btech Computer engineering from Sigma Institute of Engineering & Technology that comes under GTU (Gujarat Technological University). I have worked on web applications, Web APIs, Windows Forms, Web Forms, Tray applications and corporate websites. Programming is my hobby and I have starting writing blog to provide a platform for those who want to grow their careers as a fullstack .NET developers.

Javascript Immediately Invoked Function Expression (IIFE)

Immediately Invoked Function Expression

Immediately Invoked Function Expression abbreviated as IIFE are the javascript functions that do not need any explicit call to invoke them. They are invoked as they are defined.

Syntax of IIFE

Syntax of Immediately Invoked Function Expression
Syntax of Immediately Invoked Function Expression


As shown in the image, these functions have 2 parts:

  1. Grouping Operator – "()" is the grouping operator which isolates the function variables so that they cannot be accessed outside the function scope even if you define the variable using the var keyword
  2. Invoke Function Expression – Again it is the "()" that invokes the function while it is defined. This makes it to be invoked immediately after the definition

Purpose of IIFE

IIFEs are mainly used for creating javascript plugins that can be integrated into many of the projects as per the requirement. A JavaScript plugin is a piece of JavaScript code that serves specific webpage features like modal popup, responsive navigation, carousels, and many more.

Example of IIFE

IIFE that prints Hello World
IIFE that prints Hello World

The above example prints "Hello World". Navigate to jsFiddle to see how this code works. Here, if you try to access the variable txtToPrint outside the function, it will give "Uncaught ReferenceError: txtToPrint is not defined" error.

What if we want any variable or object to be accessed outside the function?

We can assign the IIFE to a variable and that variable can be used further as shown in the below image:

IIFE that returns a variable
IIFE that returns a variable

This is how we can access a variable that is returned by the IIFE. Navigate to JSFiddle to see how this works.

I Hope, you got a basic idea of what an Immediately Invoked Function Expression in JavaScript is. For any queries, you can write to me at [email protected]. To get notified for the releases, subscribe through email. If you found this article useful, please share it. Thank you 😊.