Is a for loops scope unique

66 Views Asked by At

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>"
              );

2

There are 2 best solutions below

1
On BEST ANSWER

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;
}
0
On

A variable in JavaScript declared inside an if or for is accessible outside the if or for after the line of code that has the declaration has been run. For instance:

function DoThing() {
    for (var i = 0; i < 1; ++i)
        var x = 0;
    return x;
}

DoThing(); // returns 0;

In the example you provided the variable is declared after reaching the body of the for loop given condition is true, or in the body of the else statement. Since those conditions are mutually exclusive it is never re-declared by that condition alone. The variable will be re-declared by the loop it is within however.

That said the code isn't very nice to read and I would recommend refactoring it to not have a for loop nested within an if statement, and not declare a new variable within both an if and an else, let alone within the body of a for loop.