神刀安全网

Immediate Invoked Function Expression in JavaScript

In this post we will be discussing about Immediate Invoked Function Expression (a.k.a IIFE) in JavaScript. IIFE is a JavaScript Design pattern which produces a lexical scope using JavaScript function scoping. In simple terms IIFE is used to place all library code inside a local scope.

How to Create Basic IIFE

(function(){

  //Your Code

}());


OR


(function(){

  //Your Code

})();

The above IIFE is an anonymous function that is wrapped inside a set of parenthesis and invoked immediately i.e. it is invoking a function expression immediately after declaring it. You can also call IIFE as function declared in expression context.

One thing to note that for IIFE you need to enclose the anonymous function inside a set of parenthesis because the JavaScript parser knows to treat the anonymous function as a function expression instead of function declaration.

Importance of Using IIFE

1. It comes in handy for the module pattern just like Modules in Node.js. Just like in Node.js Modules, variables local to the modules or IIFE will be private because it is wrapped in a function.

2. Data encapsulation is also maintained when using IIFE because it prevents properties in the global variable to be overwritten by the local variable.

3. Increases Readability of your application when using IIFEs.

Bit Careful when using IIFE

You should be bit careful in using IIFE because if not used properly it will give wrong results. For example you have the below piece of code.

var a = function(){

  console.log(‘hello’);

}


(function(){

  console.log(‘world’);

})();


which will give an error like below :

Immediate Invoked Function Expression in JavaScript

This is because the above code will run something like

var a = function(){

  console.log(‘hello’);

} (function(){  console.log(‘world’); })();


And your first function is treated like IIFE and it is called by passing your second function as parameter and tries to call the return value of the first function thus giving an error. Instead you need a semicolon after the first function or change the above code as below to differentiate the actual IIFE.

var a = function(){

  console.log(‘hello’);

}

(function(){

  console.log(‘world’);

}());

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Immediate Invoked Function Expression in JavaScript

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址