Why does a returned function from a HOF still have access to the HOF's variables?
Because of closures. The returned function holds a reference to the HOF's lexical environment. As long as the returned function exists, the environment (and its variables) cannot be garbage collected.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in The Relationship Between Closures and Higher-Order Functions
Closures are what make HOFs work. When a HOF returns a function, the returned function closes over the HOF's local variables. This lets the returned function access those variables later, even after the HOF has returned.
memoize is a HOF that returns a function. The returned function closes over a cache object. Each call checks and updates the cache. The cache persists across calls because of the closure.
No. HOFs that return functions rely on closures to persist state. Without closures, the returned function could not access the HOF's local variables (like factor in multiplier or cache in memoize). Closures are essential.
Still have questions?
Browse all our FAQs or reach out to our support team
