IIFE Javascript Es6
- What is an IIFE in JavaScript?
IIFE (Immediately Invoked Function Expression) may be a JavaScript function that runs as soon because it is defined.
(function ()
{// logic here })
();
Your first encounter could seem quite confusing but actually, the pattern is straightforward . The pattern is instantly invoked function expression.
JavaScript functions are often created either through a function declaration or a function expression. A function declaration is that the “normal” way of making a named function.
A function created within the context of an expression is additionally a function expression. The key thing about JavaScript expressions is that they return values.
In both cases above the return value of the expression is that the function.
That means that if we would like to invoke the function expression directly we just got to tackle a few of parentheses on the top . Which brings us back to the primary little bit of code we looked at:
(function ()
{ var foo = “hello”;
console.log(foo);
})
();
console.log(foo); //Error: foo is not defined
The primary reason to use an IIFE is to get data privacy. Because JavaScript’s var scopes variables to their containing function, any variables declared within the IIFE can't be accessed by the surface world.
0 Comments