Facebook Pixel

How did developers fix the var loop closure bug before let existed?

With an IIFE (immediately invoked function expression) that captured the current value of i as a parameter. Each iteration created a new function scope, so each callback closed over its own copy.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in let and const in Loops: The Closure Fix

Because let creates a fresh binding of the loop variable per iteration. Each callback closes over its own copy of i, which holds the value for that iteration. With var, all callbacks share one i, which is the final value by the time they run.

No. const i = 0; i++; throws TypeError because i++ reassigns i, and const does not allow reassignment. Use let for classic for loop counters.

Yes. Each iteration of for...of creates a fresh binding, and the loop variable does not change within an iteration. const is appropriate and preferred for for...of and for...in.

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