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 |
As shown in the image, these functions have 2 parts:
- 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
- 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 |
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 |
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 😊.