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.
(function(){
 //code here 
})(); 

Syntax 2:
 (function(){
 //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.
1.
!function(){
  //code here
}(); 
2.
~function(){
  //code here
}(); 
3.
-function(){
  //code here
}(); 
4.
+function(){
  //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.
<script>
    var a =5, b=10; 
	(function(arg1, arg2){
	    var sum = arg1 + arg2;
		alert(sum);// Output will be 15
	})(a, b);
</script> 
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.
<script>
	var message =(function(name){
		return 'Your name:' + name;
	})('Mahesh');
	alert(message); //Output: 'Your name: Mahesh'
</script> 
Find the example of IIFE which also provides private methods.
<script>
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!
</script> 

4. Reference

Immediately-Invoked Function Expression (IIFE)
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us