2
for (var a=0; a<5; a++)
{
    setTimeout(function(){
        alert(a);
    }, 0);
}

The above code in javascript is prompting me with the output of 5, 5 times infact my expectation was of the output something like 0,1,2,3,4 but rather it shows me the output of 5,5,5,5,5. Why is it so?

Besides that please explain me the concept of context and scope in javascript i always fail to understand it through many examples reading from the web.

HarshSharma
  • 630
  • 3
  • 9
  • 34
  • Why you are using setTimeout function??? – priya_singh Oct 21 '16 at 07:58
  • I was just brushing my concept of js but infact i landed doing this and now trouble understanding it :) – HarshSharma Oct 21 '16 at 07:58
  • I know this question has been asked many times before. Have you searched for an answer? – Davin Tryon Oct 21 '16 at 07:59
  • short answer: `a` is closed over in the callback and the loop finishes before the first time the callback function executes. – Davin Tryon Oct 21 '16 at 08:00
  • @DavinTryon, apologize i haven't searched because i was not aware what topic to search on google – HarshSharma Oct 21 '16 at 08:00
  • javascript is not a line by line programming language – Beginner Oct 21 '16 at 08:00
  • Scope in ES5 is extremely simple: all variables are scoped to their containing function. ES6 introduces new kinds of variables (`let` vs `var`) that are scoped to the block. – Amadan Oct 21 '16 at 08:01
  • @DavinTryon i have put the timeout to **0** still why it is showing me 5,5,5,5,5 – HarshSharma Oct 21 '16 at 08:01
  • As JavaScript is monothreaded, asynchronous timers like setTimeout() can't run immediately, even with a timeout value of 0. In fact, it's in the HTML 5 Spec (https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Reasons_for_delays_longer_than_specified) that timers should wait at least 4 ms before being executed. So in your case, the loop has ended before the first call to the alert() function is made. – nioKi Oct 21 '16 at 08:03
  • @HarshSharma same reason. Read about the JavaScript event loop. – Davin Tryon Oct 21 '16 at 08:03
  • Thanks @noKid appreciated – HarshSharma Oct 21 '16 at 08:05
  • **`setTimeout()` with 0 will only run when the stack is empty.** So when the `for` loop is finished and the stack is empty the 5 `setTimeout()` callbacks are being called and `a` is already 5 by then. – Jaqen H'ghar Oct 21 '16 at 08:06

1 Answers1

1

Inside setTimeout(), your alert() is called asynchronously so it is very likely that for loop is already finish before alert() get executed.

Zamrony P. Juhara
  • 5,222
  • 2
  • 24
  • 40