What is an “Immediately-Invoked Function Expression” (IIFE)?
is a JavaScript design pattern 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.
A “Self-executing anonymous function” or “Immediately-Invoked Function Expression”?
IIFE, pronounced “iffy”, is a pattern has been referred to as a “self-executing anonymous function”. Both terms are pointing at the same idea, but IIFE (Ben Alman) make more sense, in my opinion.
Why “Immediately-Invoked Function Expression” (IIFE) is more accurate term?
– It’s not self-executing, because it doesn’t invoke itself. It is Function Expression that gets invoked immediately, however.
– Doesn’t needs to be “anonymous” it could be since either “anonymous” or “named”.
Let’s code the words
1 2 3 |
(function(){ /* code */ }()); |
or with a name
1 2 3 |
var n = (function foo(){ /* code */ }()); |
1 2 3 4 5 6 7 8 9 10 11 |
// an anonymous function expression that gets invoked immediately, // and assign its *return value* to a variable var n = (function(){ x = "leo"; })(n); // x is now assigned to n. // n is global scope window.x; // leo window.n; // undefined |
Defining public accessors
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var n = (function(){ x = "leo"; return { get: function(){ return x; } } })(n); // x is now assigned to n. // n is global scope window.x; // leo window.n; // Object {get: function} get: function (){__proto__: Object} n.get(); // leo |
Parentheses order
Both expressions below are correct
1 2 |
(function(){}) (); (function(){}() ); |
Defensive semicolon
In JavaScript can cause problems and being interpreted as a call to the last term on the preceding line. Normally we use this if we are extending or creating a plugin.
1 2 3 |
;(function(){ /* code */ }()); |