The following code prints “true”. I can understand why ff.f is equal to undefined, but I don’t understand why console.log(“Hi”) is not executed inside ff.f when checking this value. Isn’t f immediately executed upon definition?
var ff = function(){
var f = function(){
console.log("Hi");
}();
};
console.log(ff.f === undefined);
[Edit] I guess a better way to ask this question is “When does this f function inside ff get executed?”. I think it’s weird that ff.f’s value is “undefined” if it doesn’t get executed until ff gets executed. Shouldn’t it be the function instead?
No, it is not – it is executed once it is evaluated – which in this case is when the parent function (
ff) is executed.When is
fexecutedAny IIFE will be executed once it is evaluated – any such expressions included inside of other functions will only evaluated once the function it is scoped to (wrapped in) executes:
Why
ff.fis not a functionJavaScript is function scoped but JavaScript does not provide any way to access a function’s inner scope (at least not, as far as I am aware). So when you try to access
ff.fyou are looking for a property namedfon the functionff– and by default there is no such property. Even if you did:ff.fwould still beundefined(because the IIFE does not return anything).