The output is 15 (in f, x is taken to be 10 and y is 7) with the following:
var x = 5;
function f(y) { return (x + y) - 2};
function g(h) { var x = 7; return h(x
var
s are not blocked scoped, so the last line is equivalent to
x = 10; z = g(f); console.log(z)
It should be clearer now that the value of x
was changed to 10
before f
was executed.
It is also important to note that free variables are evaluated when a function is called, not when it was defined. And of course the value of a variable can change between the definition of a function and the call of the function, just like in your example.
In the third line, x
is local to g
and therefore is completely independent from the "outer" variable x
.
See also What is the scope of variables in JavaScript?
A much simpler example that demonstrates this behavior would be:
var x = 5;
function foo() {
console.log(x);
}
x = 10;
foo(); // outputs 10