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
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.