Javascript
code:
for(var i=0; i<5; i++){
console.log(i);
setTimeout(function(){
console.log(" magic "+ i)
}, 2000);
};
outputs:
- What does the number
25
mean ? - How
i
was incremented to5
whilei++
is unreachable after4
?
Javascript
code:
for(var i=0; i<5; i++){
console.log(i);
setTimeout(function(){
console.log(" magic "+ i)
}, 2000);
};
outputs:
25
mean ?i
was incremented to 5
while i++
is unreachable after 4
?You get the numbers 0 to 4 from:
console.log(i);
and 5 times "magic 5" because you execute
console.log(" magic "+ i)
5 times after you counted i
to 5.
The more interesting part is the other number. This is the result from the last setTimeout(...)
. Everytime you execute Javascript in the console you get the return value of your code (console.log("foo")
would yield undefined
). The last statement directly executed in your code is a setTimeout
which returns an ID.