Facebook Pixel

How do you fix the classic var loop and setTimeout closure bug?

Use let instead of var (each iteration gets a fresh binding), or wrap the body in an IIFE that captures the current value of i as a parameter.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Hoisting in Loops and Conditionals in JavaScript

Because var is function-scoped. There is one i shared by all iterations. By the time the setTimeout callbacks run, the loop has finished and i equals the final value, so all callbacks log that value.

Because let is block-scoped and the spec gives each iteration a fresh binding. Each closure captures its own copy of i, so callbacks log 0, 1, 2 instead of the final value.

Yes. var ignores block boundaries (except function bodies), so a var inside an if is hoisted to the enclosing function or global scope. let and const are block-scoped and do not leak.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.