I've embarked on a mission to actually explore and try to deeply understand Javascript. On my journey I've come up with the following code and I'm troubled by the output, especially since I can't seem to explain its output yet it throws no errors:
var test = 1;
var func = function(){
console.log(test);
for(x=0;x!=1;x++) {
var test = test + x;
console.log(test);
};
};
console.log(test);
func();
I would expect the output to be:
1
1
1 (or possibly an error due to scoping issues)
What I actually get is:
1
undefined
NaN
I can buy the NaN since, in my mind, I've locally scoped a variable named test and I'm initializing it to itself plus x. I could see that as an obvious fail, yet no error is thrown. The one that really puzzles me is the "undefined." Shouldn't that output the globally scoped test?