1

Got asked this at a "Junior" Web Developer interview. They asked what is the output of

var funcs = [];
for ( var i = 0; i < 5; ++i )
{
    funcs.push(function ( ) { console.log("i = " + i); });    
}
funcs.forEach(function ( el ) { el(); });

is and they asked me to explain why. Well, I screwed up. Later I went on JSFiddle and found out that the output is

i = 5 
i = 5
i = 5
i = 5
i = 5

http://jsfiddle.net/wen3us7y/

and I figured out that it has to do with the for loop causing a closure. But still, I don't understand how the i on the right side of the expression "i = " + i is updated as i increments. I would understand if it were console.log(i) but doesn't the fact that i is in a mathematical expression make that expression an r-value???? I've never heard of a programming language where you can do something like

i = 5;
y = 2 + i;
++i;
// now y is 8

This is chaos. Society cannot function like this.

royhowie
  • 11,075
  • 14
  • 50
  • 67

1 Answers1

1

it is a closure, and the variables are scoped on function level, no block level.

So after your for loop, the i is still defined, and its value is 5, because it the last value before exiting the loop.

The console log and the string concatenation is executed in the forEach, so there i already has its value, 5

If you want to have a variable in block level, you should use let, but keep in mind it is a feature of javascript6

for ( let i = 0; i < 5; ++i )

In that case, your i in the console.log will be undefined, since i is no longer accesible

Gonzalo.-
  • 12,512
  • 5
  • 50
  • 82