Ask HN: Am I one of the few JavaScript programmers who didn't realize this
I'm currently reading "Data structures and Algorithms with Javascript" and I had a WTF! moment when I got to page 9 and read "...Javascript does not have a block scope..."
Meaning this piece of code works! Blimey!
for(var i=0; i<=10; i++){
// do nothing
}
// access 'i' out of for loop
console.log("i = " + i); // i = 11
16 comments
[ 3.0 ms ] story [ 24.7 ms ] threadAside from that: Function scope makes sense to me but I dont think I've ever gone and thought "damn it all, if only I had block scope!"
I don't think anyone really sees a problem with it, although it might be somewhat of a gotcha for people coming from languages where variables are local to the loop.
As it is, without that explanation, all I can think is, so weird language x does something weird and then its a gotcha when a language (funnily enough javascript) does it in a non weird way? I'd say sounds more like a gotcha for language x, than anything else.
Browser compatibility isn't too bad, but no Safari support it seems: http://kangax.github.io/es5-compat-table/es6/#let