Facebook Pixel

Why does for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0) log 3, 3, 3?

Because var is function-scoped. All callbacks share one i. By the time the callbacks run, the loop has finished and i is 3. Using let fixes this because let creates a fresh binding per iteration, and each callback closes over its own i.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Common Closure Interview Questions in JavaScript

A function that remembers the variables from its lexical scope, even after the outer function has returned. The function object holds a reference to its outer lexical environment, so it can access those variables later.

Use a closure with a done flag. The first call sets done to true and stores the result. Subsequent calls return the stored result without running the function again.

Create a cache object in the outer function. Return a function that checks the cache for the arguments (serialized as a key). If not found, call the original function and store the result. Return the cached result.

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