Facebook Pixel
The setTimeout Loop Closure Bug: var vs let

Do closures close over the variable or the value in JavaScript?

The answer

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.

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.

By creating a new function scope per iteration and capturing the current value of i as a parameter (j). Each callback closes over its own j, which is a snapshot of i at that iteration. This was the pre-ES6 workaround.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Your learning library

Small steps. Big possibilities.

Find your next course. Build something great.

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.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.