IIFE (Immediately Invoked Function Expression)
IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.
(function ()
{// logic here }
)
();
The pattern is immediately invoked function expression.
JavaScript functions can be created either through a function declaration or a function expression. A function declaration is the “normal” way of creating a named function.
A function created in the context of an expression is also a function expression. The key thing about JavaScript expressions is that they return values.
(function ()
{ var foo = “hello”;
console.log(foo);
})
();
console.log(foo); //Error: foo is not defined
The primary reason to use an IIFE is to obtain data privacy. Because JavaScript’s var scopes variables to their containing function, any variables declared within the IIFE cannot be accessed by the outside world.