Immediately Invoked Function Expressions in Javascript

0
357
views
Invoked Function Expressions in Javascript

Immediately Invoked Function Expressions in Javascript.

As we know when a function is invoked, a new execution context is created.
Functions defined within a function may only be accessed within the context of the enclosing function. Invoking a function in this way creates a sort of privacy.

Immediately Invoked Function Expression (IIFE) is one of the most popular design patterns in JavaScript. It pronounces like iify. IIFE has been used since long by JavaScript community but it had misleading term “self-executing anonymous function”. Ben Alman gave it appropriate name “Immediately Invoked Function Expression”

Have a look on this code snippet:


// Because this function returns another function that has access to the
// "private" var i, the returned function is, effectively, "privileged."
function makeCounter() {
// `i` is only accessible inside `makeCounter`.
var i = 0;
return function() {
console.log( ++i );
};
}
// Note that `counter` and `counter2` each have their own scoped `i`.
var counter = makeCounter();
counter(); // logs: 1
counter(); // logs: 2
var counter2 = makeCounter();
counter2(); // logs: 1
counter2(); // logs: 2
i; // ReferenceError: i is not defined (it only exists inside makeCounter)

Whether you define a function like function foo(){ } or var foo = function(){}; ultimately you have a function with an identifier.

In this case, foo that you would invoke by putting a parenthesis (); around it.

Function Declarations require a name…

As you can see, there’s a catch. When the parser encounters the function keyword in the global scope or inside a function, it treats it as a function declaration, and not as a function expression.

If you don’t explicitly tell the parser to expect an expression, it sees what it thinks to be a function declaration without a name and throws a syntax error because function declarations require a name.

…Or do they? Introducing the Immediately-Invoked Function Expression (IIFE)

There are actually several ways to tell the parser to expect a function expression without a declaration just to wrap it in parentheses because, in JavaScript, parentheses cannot contain statements.

Instead, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.

// Either of the following two patterns can be used to immediately invoke
// a function expression, utilizing the function's execution context.
(function(){ /* code */ }()); // Douglas Crockford recommends this one
(function(){ /* code */ })(); // But this one also
// Because the point of the parens or coercing operators is to disambiguate
// between function expressions and function declarations, they can be
// omitted when the parser already expects an expression (but please see the
// "important note" below).
var i = function(){ return 10; }();
true && function(){ /* code */ }();
// If you don't care about the return value, or the possibility of making
// your code slightly harder to read, you can save a byte by just prefixing
// the function with a unary operator.
// This will ensure that the parser knows a function expression is happening
!function(){ /* code */ }();
~function(){ /* code */ }();
-function(){ /* code */ }();
+function(){ /* code */ }();

A note about the parenthesis around a function:

In cases where the extra “disambiguation” parenthesis surrounding the function expression are unnecessary (because the parser already expects an expression), it’s stilla good idea to use them when making an assignment, as a matter of convention.

Such parenthesis typically indicates that the function expression will be immediately invoked, and the variable will contain the result of the function, not the function itself.

This can save someone reading your code the trouble of having to scroll down to the bottom of what might be a very long function expression to see if it has been invoked or not.

Saving state with closures Just like when arguments may be passed when functions are invoked by their named identifier, they may also be passed when immediately invoking a function expression.

And because any function defined inside another function can access the outer function’s passed-in arguments and variables (a closure)

Immediately-Invoked Function Expression can be used to “lock in” values and effectively save state.

LEAVE A REPLY

Please enter your comment!
Please enter your name here