Immediately-Invoked Function Expression (IIFE) JavaScript Tutorial | Self-Executing Anonymous Function Example

By Arvind Rai, March 08, 2016
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.

Syntax for using Immediately-Invoked Function Expression

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.

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.

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!


Wikipedia: Immediately-invoked function expression
Ben Alman: Immediately-Invoked Function Expression (IIFE)

©2023 | Privacy Policy | Contact Us