DEV Community

Discussion on: 10 JavaScript Interview Questions

Collapse
 
aybee5 profile image
Ibrahim Abdullahi Aliyu

Hey, can you please explain no 2 more? Why will it be all 5

Collapse
 
olvnikon profile image
Vladimir • Edited

Let's first understand how the loop works.

for (var i = 0; i < 5; i++) {
Enter fullscreen mode Exit fullscreen mode
  1. var i = 0 - the first thing that happens
  2. i < 5 (0 < 5) is TRUE then we execute the loop
  3. i++ (i = 1 now)
  4. i < 5 (1 < 5) is TRUE then we execute the loop
  5. i++ (i = 2 now)
  6. ...
  7. i < 5 (4 < 5) is TRUE then we execute the loop
  8. i++ (i = 5 now)
  9. i < 5 (5 < 5) is FALSE then we stop executing the loop

At the end of the loop i = 5 (not 4). The loop repeated 5 times (i = 0,1,2,3,4).
When setTimeout starts to execute the function it uses the global "i", which is 5, and executes it 5 times hence you see "5" five times.

UPD: replaced "let" by "var". Copied from the wrong place. There are no issues with "let".