Facebook Pixel

Why does let in a for loop fix the closure bug with setTimeout?

Because let creates a fresh binding per iteration. Each callback closes over its own copy of i, so they log 0, 1, 2. With var, all callbacks share one i, so they all log the final value.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Closures and the Scope Chain: Real-World Examples

By declaring a variable inside a function and returning methods that access it. The variable is not accessible directly from outside, only through the returned methods. This is the module pattern.

The memoize function closes over a cache object. The returned function checks and updates the cache without exposing it. Each call returns the cached result if available, otherwise computes and stores it.

It closes over a done flag and a result variable. The first call sets done to true and stores the result. Subsequent calls return the stored result without running the function again.

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.