Immediately-Invoked Function Expression (IIFE) JavaScript Tutorial | Self-Executing Anonymous Function Example
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.
(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 }();
~function(){ //code here }();
-function(){ //code here }();
+function(){ //code here }()
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>
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>
<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>
References
Wikipedia: Immediately-invoked function expressionBen Alman: Immediately-Invoked Function Expression (IIFE)