What is IIFE in Javascript ?

An IIFE is an anonymous function that is created and then immediately invoked. It's not called from anywhere else (hence why it's anonymous), but runs just after being created.


It has nothing to do with any event-handler for any events (such as document.onload).
The first pair of parentheses (function(){...}) turns the code within (in this case, a function) into an expression, and the second pair of parentheses (function(){...})() calls the function that results from that evaluated expression.
This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.
(function(){
    // all your code here
    // ...
})();
// foo is unreachable here (it’s undefined)

Comments

Popular posts from this blog

What is MQTT protocol & its use

What the hack is Call, bind & apply