Explain Closures

Talk it through out loud with your AI coach.

The problem

  • medium
  • Pro

You need a function called makeCounter. Each call to it returns a new counter function, and each time you call a counter it returns the next number, starting at one. Two counters must count independently, and nothing outside should be able to change a counter's number. Explain how you'd build it and why it works.

What a strong answer covers

  • Where the counter's number lives so it survives between calls.
  • How an inner function keeps access to variables after its outer function has finished.
  • Why each counter keeps its own count.
  • How this pattern keeps data private, and where else it shows up.

Common mistake: Keeping the count in a variable outside the factory, so every counter shares one number.

Knowing this is half of it. Saying it clearly out loud is the part the coach helps you practise.

Practise it out loud