What is a closure in JavaScript, and what does this log?
function counter() {
let n = 0;
return () => ++n;
}
const c = counter();
c(); c();
console.log(c());Options
- 3: the inner function remembers its outer
n(Correct option) - 0: each call starts again from zero every time
- undefined:
nis not visible outside of it - 1: only the first call changes the value of n
Answer
3: the inner function remembers n from where it was created
Why
A closure is a function that keeps access to the variables of the scope where it was created, even after that outer function finished.
counter() returns an arrow function that still sees its own private n. Each call increments the same variable: 1, 2, then 3. No outside code can touch n directly (data privacy).
Closures power callbacks, event handlers and React hooks.
Remember
Closure = function + remembered variables.