Facebook Pixel

What is the fundamental difference between var and let in a for loop with closures?

var creates one shared i for the entire loop; all closures see the final value. let creates a fresh i per iteration; each closure sees its own value. This is the key to the setTimeout loop closure bug.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in The setTimeout Loop Closure Bug: var vs let

Because var is function-scoped. There is one i for the entire loop. All callbacks close over the same i. By the time they run (after the loop), i is 3. Closures close over the variable, not the value.

Because let is block-scoped and creates a fresh binding per iteration. Each callback closes over its own copy of i, which holds the value for that iteration. So when they run, each sees its own value.

The variable. A closure holds a reference to the variable, not a snapshot of its value. If the variable changes before the callback runs, the callback sees the updated value. This is why var in a loop logs the final value.

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.