Search code examples
scoperefactoringjshintvariable-declarationtechnical-debt

Is a for loops scope unique


I ran into this while performing some technical debt duties. What is the scope of the variable foo ? Is it really "already defined"?

function fn(){
    for (var i = 0; i < m.length; i++) {
        if(condition)
            for (var j = 0; j < m.length; j++) {
                var foo = "bar";
            }
        else 
            var foo = "fubar"
    }
}

UPDATE: The question is about the scope of the variables defined within a conditional block. Since this isn't nested in a function/closure there is no unique scope.

Here is a snippet to illustrate:

var x = "foo",
    a = [];

for(var i=0;i<10;i++){
  var x = {value:1+i};
  a.push(x)
}

document.write("<pre>" + 
               x.value + "\n" + 
               JSON.stringify(a,null,"  ") + 
               "</pre>"
              );


Solution

  • JavaScript only has function scope, not block scope. So your variable foo exists at function level and both assignments refer to same instance.

    var m = [ 1, 2, 3 ];
    var x = fn(m, true);
    WScript.Echo( x );
    var x = fn(m, false);
    WScript.Echo( x );
    
    function fn(m, condition){
        for (var i = 0; i < m.length; i++) {
            if(condition)
                for (var j = 0; j < m.length; j++) {
                    var foo = "bar";
                }
            else 
                var foo = "fubar"
        }
        return foo;
    }