javascriptloopsfor-loopredeclaration

Redefining a variable in a loop does not make it undefined


Having the following for-loop:

for (var i = 0; i < 3; ++i) {
    console.log(i, p);
    var p;
    p = 42;
}

I was expecting the output to be:

0 undefined
0 undefined
0 undefined

But actually, the output is:

0 undefined
0 42
0 42

Since we're using var p (to redeclare p) next line, why isn't p undefined (always) in the console.log line?


Solution

  • due to variable hoisting and your variable being function scoped rather than block scoped.

    your for loop is translated to

    var p;
    for (var i = 0; i < 3; ++i) {
        console.log(i, p);
        p = 42;
    }
    

    which means first time p is accessed it is undefined,

    Next time it is already initialized in the current function scope so it will be keep the initialized value.