JavaScriptQuestion 08 of 36
What is closure?
Answer out loud or in your head first, then compare.
Answer
A closure means a function remembers the scope in which it was created.
JavaScript
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
counter(); // 1
counter(); // 2
counter(); // 3Even though createCounter() has already finished, the inner function still has access to count.
Uses:
- private state,
- callbacks,
- factory functions,
- event handlers,
- memoization.
How did it go? Be honest — “Not yet” puts the question on your review list.
Related questions
- B-P07 · What is a closure? — JavaScript, TypeScript and Node.js
Practise in code
- Write debounce — runs tests in your browser