-2

Javascript code:

for(var i=0; i<5; i++){
  console.log(i);
  setTimeout(function(){
    console.log(" magic "+ i)
  }, 2000);

};

outputs:

output

  1. What does the number 25 mean ?
  2. How i was incremented to 5 while i++ is unreachable after 4?
BalaajiChander
  • 139
  • 3
  • 21

1 Answers1

0

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.

danielspaniol
  • 2,228
  • 21
  • 38