Ask HN: Am I one of the few JavaScript programmers who didn't realize this

22 points by wilsonfiifi ↗ HN
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 ] thread
Yes, it should be one of the first things you learn when learning JavaScript. JavaScript only has function scope, meaning that you only get new scope inside of a function.
Yep, this and hoisting is something I expect any JavaScript developer to know.
Yeah, but there's this:

  array.forEach(function(value, index) { ... });
Hopefully, but probably not. There are probably only slightly less bad JavaScript programmers as there are bad PHP programmers.
Blimey is right. Although I would guess for most people their first encounter would be something like this:

  var foo = function(callback) { callback(); }
  
  for(var i=0; i<=10; i++){
    setTimeout(function() {
      console.log("i = " + i);
    }, 100);
  }
Which, if you don't know what to look for, is a bit of a brain melter. Between that and [1,2,10].sort(), there are lots of great reasons to yell at your screen when learning JS.
Correct me but, atm, it would be possible to use the keyword "let" to declare a local variable with a block scope if I remember well, isn't it?
Same thing with Python and PHP.
Am I the only one who doesn't see a huge problem with this? Its actually kinda handy sometimes to have the last value / index of your array defined outside after the loop. Same goes for variables defined within the loop.

Aside 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!"

Am I the only one who doesn't see a huge problem with this?

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.

And it doing the opposite would be a gotcha for anyone else. Is anyone able to explain why a language would have block scoping in the first place? Is it a good thing and I just don't know? I really hope its not because of the braces.. That would be kind of silly.

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.

I hate Javascript... and recently I have gone mad over Node.js "server side javascripting..."
Hey, cool. I guess I knew that but didn't really 'know' it. Thanks.