Immediately invoked function expression (IIFE)

An immediately-invoked function expression (IIFE) is a JavaScript programming language idiom which produces a lexical scope using JavaScript’s function scoping. Immediately-invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.

Example

The function becomes a function expression which is immediately executed. The variable within the expression can not be accessed from outside.

(function () { 
    var aName = "Barry";
})();
// Variable name is not accessible from the outside scope
aName // throws "Uncaught ReferenceError: aName is not defined"

Assigning the IIFE to a variable does not store it but its result.

var result = (function () { 
    var name = "Barry"; 
    return name; 
})(); 
// Immediately creates the output: 
result; // "Barry"