7

I remember variables are function scoped in Javascript. But, how is the behavior if I redefine the local variable in a loop. One common use case is nested loops. In the below code, if I change j to i, the outer for loop terminates after one iteration as the value of i in outer scope is same as inner for loop. Since I use var, I was expecting (similar to other language) it is redefined inside inner fo loop. Does this mean in JS, there is no way to redeclare and use local variable within function scope.

for (var i = 0, len = x.length; i < len; i++) {
            ...
            for (var j = 0, len = y.length; j < len; j++) {
                ...
            }
        }
bsr
  • 57,282
  • 86
  • 216
  • 316
  • 3
    JavaScript does not have block level scope, only function level, so *Does this mean in JS, there is no way to redeclare and use local variable within function scope.* -> Yes, it means just that – Matt Sep 25 '12 at 12:56
  • More on Matt's thing [here](http://stackoverflow.com/q/643542/645270) – keyser Sep 25 '12 at 12:57

3 Answers3

8

As you said, JavaScript only has function scope. Variable declarations are hoisted to the top of the scope in which they are declared. Your example is interpreted like this:

var i, j, len; //Declarations are hoisted...
for (i = 0, len = x.length; i < len; i++) { //Assignments happen in place
    for (j = 0, len = y.length; j < len; j++) {

    }
}

As for this part:

if I change j to i, the outer for loop terminates after one iteration

If you replace j with i, then after the first iteration of the inner loop, i will be y.length - 1, and the outer loop will either continue or stop, depending on the difference between x.length and y.length.

If you're interested in the real explanation of the internal workings, the ECMAScript spec (Declaration Binding Instantiation) covers it in detail. To summarise, every time control enters a new execution context, the following happens (a lot more than this happens, but this is part of it):

For each VariableDeclaration and VariableDeclarationNoIn d in code, in source text order do

  • Let dn be the Identifier in d.
  • Let varAlreadyDeclared be the result of calling env’s HasBinding concrete method passing dn as the argument.
  • If varAlreadyDeclared is false, then
    • Call env’s CreateMutableBinding concrete method passing dn and configurableBindings as the arguments.
    • Call env’s SetMutableBinding concrete method passing dn, undefined, and strict as the arguments.

This means that if you declare a variable more than once per execution context, it will effectively be ignored.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
4

Every var declarement will be put into the top of the current scope, so your code is same as:

   var i, j, len;
   for (i = 0, len = x.length; i < len; i++) {
        ...
        for (j = 0, len = y.length; j < len; j++) {
            ...
        }
    }

Check this: JavaScript Scoping and Hoisting

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Are you not missing `len` from the var list? I would have added it myself, but I'm doubting myself as @James has missed it out as well :P. – Matt Sep 25 '12 at 12:58
  • @xdazz: He does, inside both loops using the `var` keyword (along with the `i` and `j` :P). – Matt Sep 25 '12 at 13:03
0

There's no block level scope in JS.

But if it's utmost necessary to have/re-declare the same variable name in your code, you can do:

function loopIt(arr, fn, scope) {
    for (var i = 0, len = arr.length; i < len; i++) {
        fn.call(scope || this, arr[i], i, arr);
    }
}

And use it like:

var firstArr = ["a", "b"];
var secondArr = ["c", "d"];

loopIt(firstArr, function(item, i) {
    var msg = "Hey it's '" + item + "'";
    console.log(msg);

    // if you want access to the parent scope's var
    var scopedItem = item;

    loopIt(secondArr, function(item, i) {
        var msg = "Hello it's '" + item + "' in '" scopedItem + "'";
        console.log(msg);
    });
});

That will give us results of:

Hey it's 'a'
Hello it's 'c' in 'a'
Hello it's 'd' in 'a'
Hey it's 'b'
Hello it's 'c' in 'b'
Hello it's 'd' in 'b'
Kenny Ki
  • 3,400
  • 1
  • 25
  • 30