HeadlinesBriefing favicon HeadlinesBriefing.com

JavaScript Closure Quiz Explained: Why Reset Fails

DEV Community •
×

A recent LinkedIn poll asked developers what a simple counter function would output. The function creates a closure around a local count variable, exposes increment, getCount, and a buggy reset that shadows the original. After two increments and a reset, the console logs 2.

The bug stems from let introducing a new block‑scoped count inside reset, which shadows the outer variable. The closure still points to the original, so the reset call does nothing. Understanding this nuance prevents silent state errors in larger codebases.

This pattern surfaces in React hooks, event handlers, and any encapsulated business logic. Misreading closures can lead to hard‑to‑trace bugs that surface only after a few interactions. Developers often overlook the difference between capturing a variable and copying its value.

To fix the counter, replace the inner let with a direct assignment: count = 0. This correct reset updates the captured variable. Adopting such best practices and using debugging tools that expose closure scopes helps maintain predictable state across complex applications.