+ 2

Infinite Loop Trap on JavaScript

This is my code for (let i = 0; i < 5; i++) { setTimeout(() => console.log(i), 1000); } Why does this print 5 five times instead of 0,1,2,3,4? How can we fix it? Please 🙏

1st Oct 2025, 7:29 AM
Alex Bright
Alex Bright - avatar
2 Réponses
+ 2
Normally with 'let' your code should print 0,1,2,3,4 (because 'let' is block-scoped inside the loop). If it printed 5 five times it might be due to an older JS environment (or you used 'var' instead of 'let' because 'var' is function-scoped). To be safe you can wrap i in a closure like this: for (let i = 0; i < 5; i++) { setTimeout((j => () => console.log(j))(i), 1000); }
1st Oct 2025, 8:19 AM
Riyadh JS
Riyadh JS - avatar
+ 1
It displays everything as it should. From 0 to 4. This code displays from 1 to 5 for (let i = 1; i <= 5; i++) { setTimeout(() => console.log(i), 1000); } 5 to 5 var num = 5; for (let i = 1; i <= 5; i++) { setTimeout(() => console.log(num), 1000); } infinity loop with break for (let i = 1; ; i++) { if (i > 8) break; console.log(i); }
1st Oct 2025, 7:40 AM
Yaroslav Vernigora
Yaroslav Vernigora - avatar