DEV Community

[Comment from a deleted post]
Collapse
 
val_baca profile image
Valentin Baca

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.