Closures
A closure is a function plus the variables it remembers from where it was
written. When a function returns another function (or a group of them), those
inner functions keep access to the outer function's variables forever - even
after the outer function has finished running and nothing else can see inside
it.
That's how you get real private state in JavaScript: a variable declared
inside a factory function is invisible from the outside, but any function
returned from that factory can still read and change it. Call the factory
again and you get a brand-new variable, completely separate from the first
one - each call builds its own private world.
Your task: write makeCounter(), a function that returns an object with
two methods: increment(), which adds 1 to a hidden counter and returns the
new value, and value(), which returns the current count without changing it.
Nothing outside the returned object should be able to read or set the counter
directly.
You'll practice:
Returning functions that share one captured variable
Building private state with a closure instead of a public property
Show a hint
Show solution
Related reading: Closures You'll Actually Write →
Previous Next