Skip to content
Discussion options

You must be logged in to vote

The difference comes from how JavaScript handles variable scope.

var is function-scoped, meaning all loop iterations share the same variable i. By the time the callbacks execute, the loop has already finished and i is 3. Therefore, all callbacks print 3.

On the other hand, let is block-scoped. In a for loop, JavaScript creates a separate binding for each iteration, allowing each callback to retain its corresponding value.

setTimeout() schedules the callbacks to execute later, after the synchronous loop has finished.

That's why var produces 3, 3, 3, while let produces 0, 1, 2.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by rheillunio2-byte
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Code Search and Navigation Search, navigate, and understand code on GitHub Question Ask and answer questions about GitHub features and usage source:ui Discussions created via Community GitHub templates Other Features and Feedback Discussions that fall into "Other" category
2 participants