If I place a self-executing JavaScript function inside a 'normal' function, when is it executed?
function normalFunction() {
var a = 1;
(function() {
var b = 2;
var c = 3;
})();
var d = 4;
}
The IIFE will only be invoked if you call normalFunction. Even though the function block will be parsed at load time, the invocation doesn't happen until the enclosing function runs, and then the IIFE gets called with the empty parameter block - ()
It's almost identical to what would happen if you had written:
function normalFunction() {
var tmp = function() {
...
};
tmp();
}
where clearly tmp() only happens during calls to the enclosing function.
awill be seen in self-executing function.bandcwon't be seen outside self-executing function.