re: The gotchas of the var keyword in JavaScript VIEW POST

FULL DISCUSSION
 

This is one of the biggest differences between Javascript and block-scoping languages like C/C++/Java/Python/Ruby/etc and the most common gotcha of the language.

Javascript took the block syntax from C but does not have block scoping.

function foo(arr) {
  for(var i = 0; i < arr.length; i++) {
    /**/
  }
}
/* Should always be thought of as: */

function foo(arr) {
  var i; // this got yanked up here
  for(i = 0; i < arr.length; i++) {
    /**/
  }
  // because you can still use i here!
}

/* and in fact, some style guides suggest the latter to make it obvious */

And yes, always use var

It's a bit dated by today's standards, but Javascript The Good Parts is a must-have IMO for anyone writting Javascript.

P.S. Good on you for using MDN. Quality docs though some other website-that-shall-not-be-named often gets the top Google results.

 

Thanks, that code snippet makes what's happening much clearer! Very unexpected behavior for someone coming from C#, gotta say. And thanks for the reading suggestion.

Lol, that other site doesn't seem as bad as it used to (I remember someone even wrote a Chrome plugin way back that removed it from search results), but with how phenomenal their docs are I'd hope MDN would be at the top of the results.

code of conduct - report abuse