Immediately-Invoked Function Expression (IIFE) in JavaScript

By Arvind Rai, November 21, 2023
On this page, we will provide Immediately-Invoked Function Expression (IIFE) JavaScript tutorial with example. Immediately-Invoked Function Expression is also known as Self-Executing Anonymous Function or sometimes Self-Invoked Anonymous Function. Immediately-Invoked Function Expression (IIFE) name has been proposed by Ben Alman and now Self-Executing Anonymous Function is commonly known as Immediately-Invoked Function Expression (IIFE). IIFE is a JavaScript design-pattern. IIFE variable has lexical scope. Lexical scope is "part of program" or "portion of run time". The variable defined within function can only be accessed within function by its name. IIFE is used to avoid variable hoisting. Here on this page we will provide IIFE syntax details and examples.

1. Syntax for using IIFE

IIFE can be used in the code with different syntaxes.
Syntax 1: This is commonly used syntax. We will use it in our examples.
 //code here 

Syntax 2:
 //code here 

Syntax 3: IIFE can also be used with unary operators. We should use these syntaxes only when if function is not returning value.
  //code here
  //code here
  //code here
  //code here
These syntaxes are not commonly used because of readability point of view.

2. Pass value to IIFE

Now lets us start to work with IIFE. Find the first example which is showing how to pass the parameters to function.
    var a =5, b=10; 
	(function(arg1, arg2){
	    var sum = arg1 + arg2;
		alert(sum);// Output will be 15
	})(a, b);
When we run the above script, the output will be 15.

3. Return value from IIFE

Find the example to get return value using IIFE.
	var message =(function(name){
		return 'Your name:' + name;
	alert(message); //Output: 'Your name: Mahesh'
Find the example of IIFE which also provides private methods.
var message = (function(){
  var msg = 'Default Message';
  return {
    getMsg: function(){
      return msg;
    setMsg: function(data){
      msg = data;
alert(message.getMsg());// Output: Default Message
message.setMsg('Hello World!');
alert(message.getMsg());// Output: Hello World!

4. Reference

Immediately-Invoked Function Expression (IIFE)

©2024 | Privacy Policy | Contact Us