var f = function () { var n = 42; return function () { return n; }; }(); var result = f(); alert(result);

f

n

42

var f2 = function () { return n; }; var f = function () { var n = 42; return f2; }(); var result = f(); alert(result);

n is not defined

n

f2

window

window.n

undefined





Take a look at the below code:The functionis a self-invoking function that returns a function, that returns the variabledeclared in the outer function.The alert of the above code is, as you'd expect,Now let's try rewriting the above code so that instead of returning a function that is declared internally, it now returns a function that was defined outside (but that does the same thing):This should return the same result, no?Actually, we are greeted with the following error:This is because of JavaScript's static scoping , also known as lexical scoping, becauseThis means that the scope of the variable is determined at compile-time, and from the second code snippet we can see that during compile time variableof functionhas) as it's scope; and since n doesn't exist in the global scope, it is