Important: JavaScript does not have block scope.

I’m a little embarrassed to say that I only looked this up for the first time today. Although, I’ve been programming in JavaScript for so long that I must have known this years ago, but “forgotten” as I haven’t done much JavaScript programming in the last few years. Hey, at least I retained that niggling feeling like I had to look that up!

Important: JavaScript does not have block scope.


 var x = 1;
 { var x = 2; }
 print( x ); // outputs 2

6 thoughts on “Important: JavaScript does not have block scope.

  1. Oh my. Bookmarked for future reference. I’ve always kind of wondered how attributes/fields and local variables worked in JavaScript whenever I really use it–but I never really checked it up. *lazy* So there _really_ is no difference. Eep. Must be really careful from now on. Thanks muchly, jj5!

    • Hey Key, just to clarify, the block level scoping applies to local/global variables, not to attributes/fields. If you want to store an attribute/field you typically reference the object you want the attribute/field on, e.g. this.field = “value” or that.field = “value”. Local variables get stored in the function’s closure, which is a whole other topic. :P If you need to scope a variable you can create a new scope by creating a closure by creating and calling a local function, e.g.

      var x = 1;
      (function() { var x = 2; })();
      print( x ); // outputs 1

      But be careful, because:

      (function() { x = 2; })(); // note: no ‘var’ keyword
      print( x ); // outputs 2! (It modified the value in the containing scope)

  2. Oh woops! Wrong terms I used! And thank you for the examples! I do remember having to use the var keyword twice when I had two variables with the same name so I understood them quickly. ^^ …When one uses such a clean-looking language like Python for a few days and then look back at something like JavaScript, the person cannot be faulted if their mind goes ‘processing wall of text. shutting down.’, yes?

    • Hehe. I for one much prefer JavaScript to Python, although I’ve been using JavaScript pretty intensively for a long time and have done close to nothing with Python. I just really like using curly brackets.. :P

      I have some pretty seriously heavy-duty work to do with JavaScript on my plate now. I plan to port each and every one of the functions at to — so I’ll be battling some very complicated ‘wall of text’-like JavaScript functions in the near future.

      Programmers truly are masochists. :P

  3. Pingback: Python hat was on « Jenny's Blog

Leave a Reply