35 ms·
I feel dumb now because I fear I don't understand what you mean when you say block scope... for(var i=0; i<3; i++) { console.log(i); } appears to be valid
by drivebyacct2 16y ago
I feel dumb now because I fear I don't understand what you mean when you say block scope...
for(var i=0; i<3; i++) { console.log(i); }
appears to be valid... (or just in Chrome?)
- aboodman 16y agoValid, just doesn't do what you think. function foo() { var x = 1; if (true) { var x = 2; var y = 3; } console.log(x); console.log(y); } foo(); // 2, 3 (vs 1, undefined if there was block scope)
- drivebyacct2 16y agoThanks for the explanation!
- pornel 16y agoJS performs "variable hoisting", so your example is interpreted as: function(){ var i; … for(i=0; … It has surprising side effects: alert(i); var i; works and outputs "undefined", which is value of the variable i that is defined. alert(k); var i; This is an error, and will fail to execute because of undefined variable.