How does a once utility use closures in JavaScript?
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.
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.
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.
Still have questions?
Browse all our FAQs or reach out to our support team
