I'm trying to reproduce deceze's answer to Is using 'var' to declare variables optional? with the following (adapted) Node.js script:
var foo = "I'm global";
var bar = "So am I";
function myfunc() {
var foo = "I'm local, the previous 'foo' didn't notice a thing";
var baz = "I'm local, too";
function innermyfunc() {
var foo = "I'm even more local, all three 'foos' have different values";
baz = "I just changed 'baz' one scope higher, but it's still not global";
bar = "I just changed the global 'bar' variable";
xyz = "I just created a new global variable";
}
}
console.log(xyz)
However, this leads to a
console.log(xyz)
^
ReferenceError: xyz is not defined
However, as I understand from his answer this should be "I just created a new global variable"
, because it was defined without the var
keyword and therefore 'bubbles up' until it reaches and attached to the global object.
Why is this not the case?
(I also have a second question: in the original answer the function names myfunc
and innermyfunc
were not there, but this leads to a SyntaxError
. Is it not allowed to define anonymous functions in Node?)