Java Reference
In-Depth Information
Immediately Invoked Function Expressions
An Immediately Invoked Function Expression (or IIFE, pronounced “iffy”) is a function
that, as the name suggests, is invoked as soon as it's defined. This is easily achieved by pla-
cing parentheses at the end of the function definition (remember that we use parentheses to
invoke a function). The function also has to be made into an expression, which is done by
placing the whole declaration inside parentheses, as can be seen in this example:
(function(){
var temp = "world";
console.log("Hello " + temp);
}());
<< "Hello world"
IIFEs are a useful way of performing a task while keeping any variables wrapped up within
the scope of the function. This means that the global namespace is not polluted with lots of
variable names.
Temporary Variables
There is no way to remove a variable from a scope once it's been declared. If a variable is
only required temporarily, it may cause confusion if it's still available later in the code. Even
worse, the name of the variable may clash with another piece of code (an external JavaScript
library, for example) resulting in errors. Placing any code that uses the temporary variable
inside an IIFE will ensure that it's only available while the IIFE is invoked, and then it will
disappear. The example that follows uses an IIFE to swap the value of two global variables,
a and b . This process requires the use of a temporary variable, called temp , which only ex-
ists while the IIFE is invoked:
a = 1;
b = 2;
(function(){
var temp = a;
a = b;
b = temp;
Search WWH ::




Custom Search