A small JavaScript oddity?
The more you work with JavaScript, the better you understand its nuances. One particular gotcha that forms a great technical interview question is what is the produced output from the following snippet of code:
1 2 3 |
for(var i=1; i<=5; i++){ setTimeout(function(){console.log(i);},0); } |
Obviously the result is:
Right? Given that the timeout is zero, so the code executes immediately doesn’t it?
If fact, the output is:
That is because, by the time the loop exits the value of i has been incremented to 4 before termination.
The important factor to note here is the single-threaded nature of JavaScript.
In fact, what is happening is that the loop executes to completion before any event handlers fire (i.e the setTimeout). By the time they do fire, i===4 and therefore it is written out as per the above.
In other languages such as C#, Java etc. this would have output as expected,but with JS? Nope.
Understanding this is key to understanding eventing in JavaScript.