I hit a subtle bug which has been distilled as follows:
function huh() {
for (var i = 0; i < 10; i++) {
if ( i % 2 == 1 ) {
var x = i;
console.log(i + ' ' + x);
}
else {
console.log(i + ' ' + x);
}
}
}
huh();
Firstly, I would challenge even experienced JavaScript programmers to correctly predict the exact output of this program on paper only. But mainly, JavaScript seems to be mixing dynamic and lexical scoping. And it seems there is no block scope, only function scope, which is basically blowing away my whole concept of scoping in JavaScript. Can someone explain in reference to the standard, and maybe a bit of rationale? This seems highly counter-intuitive.