More weird JavaScript: variable scope
I know I'm going to get "only a n00b would not know that" comments, but I'm sure this will help some folks out there, so here it goes.
Eilon pointed out to me this morning this weird and very counter-intuitive behavior of JavaScript. Basically, there is no block scope for variables...
var x=1;
if (true) {
var x=2;
if (true) {
var x=3;
alert(x);
}
alert(x);
}
alert(x);
outputs 3 three times, whereas in all other curly brace languages that I know, you'd get 3, 2 and 1.
Except that there is variable scope... Only in functions and script blocks. That's what enables OO programming using closures.
To summarize: variables in JavaScript are only local to functions, not to any other kind of {} block.
If anybody has a good explanation for why JavaScript goes against all tradition from its ancestor language (C), I'd be genuinely interested in knowing it.
(thanks to David and Karsten for some insights on this issue)