I thought declaring something with "var" made it local to its scope.
It does: Function scope (or global scope if you use it globally). Unlike variable declarations in many similar languages, var
doesn't have block-scope. So your loop is terminating after outputting just one line because you're setting len
to 1
in the initializer of the inner loop, and that's the same len
as the one being used by the outer loop.
That and some other aspects of var
were sufficiently troublesome that it's been fixed: In ES2015 (the latest JavaScript specification), the new let
has block scope (and there's some special hand-waving around for
loops), so your example would work with let
:
// NOTE: Only works on browsers supporting `let`!
"use strict"; // (Some browsers don't support let outside of strict mode yet)
for (let i = 0, len = 3; i < len; i++) {
for (let j = 0, len = 1; j < len; j++) {
console.log('i=' + i + ', j=' + j + ', len=' + len);
}
}
But I wouldn't recommend using two nested len
s like that. Even though JavaScript won't get confused, there's no guarantee the programmer coming after you won't.
let
is one of the several really good things about ES2015. In all but a very few edge cases, let
is the new var
. Of course, until all of your target browsers have updated their JavaScript engines, you have to either stick with var
or transpile.