I came across an interesting question on Reddit. Someone was having trouble understanding why two different approaches to counting values in JavaScript didn’t behave the same way.
The Reddit user expected that two similar ways of incrementing a counter would reset the count to zero, but they didn’t.
The Reddit user was confused. They thought the first and second approach should behave the same way, but they don’t. The first approach resets the count to zero every time, while the second approach continues from where it left off.
Why Does This Happen?
The key difference lies in closures. If that word makes your head spin, don’t worry—I’ll break it down.
A closure in JavaScript happens when a function can “remember” and access variables from the outer scope, even after that outer function has finished executing. This allows the inner function to maintain access to the variables in place when the function was created.
outerFunction()
is called, which creates a local variableouterVariable
and defines aninnerFunction
.outerFunction()
then returnsinnerFunction
, but here’s the magic part: even though outerFunction has finished running, theinnerFunction
can still accessouterVariable
. This is because of closure.
The innerFunction
“remembers” the environment where it was created, which includes the outerVariable
variable. When you call closureFunction()
, it can still access and log the outerVariable
even though the outerFunction()
has completed execution.
Simple Counter Using Closures
createCounter()
defines a localcount
variable and returns a function that increments and logs the value ofcount
.- Even after
createCounter()
finishes, the returned function still has access to the count variable thanks to closure. So, every time you callcounter()
, it updates the same count variable, preserving the value between calls.
Closure with Parameters
Let’s expand the counter to take an initial value as a parameter.
- This time, we pass an initial value (
startValue
) tocreateCounter()
. The count variable is initialized with this value. - When you create two counters (
counterFrom10
andcounterFrom5
), each has its independent count variable, but both preserve their state between calls. Each closure remembers its starting value.
Multiple Functions Sharing the Same Closure
Now, let’s say you want to create a counter that can increment, decrement, or reset the count. Here’s how you can do that using closures.
- We’re returning an object that contains multiple functions, all of which share access to the same
count
variable. - Each method (
increment
,decrement
,reset
) is a closure, and they all share the same count state. So, whether you increment, decrement, or reset, they’re all working with the same count variable that’s kept alive by the closure.
First Approach: Why Does It Reset?
In the first approach:
Every time you call createCount()
, you are creating a new instance of the count variable.
- The first
createCount()
call creates a freshcount = 0
, increments it to 1, and logs it. - The second
createCount()
call does the same thing: it creates a newcount = 0
and increments it again to 1.
This is why the count resets in this approach—it’s like hitting the “reset button” every time you call createCount()
.
Second Approach: Why Does It Continue?
Now, look at the second approach:
Here, you’re only calling createCount()
once. This is crucial because you’re saving the result (which is the increment
function) into the counter
variable.
- The first time you call
counter.increment()
, it uses the count that was initialized as 0 in the originalcreateCount()
. It increments the count to 1. - The second time you call
counter.increment()
, it doesn’t reset count. It just uses the same count value that’s now 1 and increments it to 2.
Since you’re not calling createCount()
again, you’re using the same closure, and the count value persists between calls.
Closures are super useful because they let you “remember” values in your functions, even after those functions have finished running. In real-world applications, closures are the backbone of things like:
- Event listeners that need to remember some information.
- Callbacks where the function is called much later but still needs access to earlier variables.
- Private variables, where you want to keep a value hidden from the outside world.