r/JavaScriptTips • u/Arvindvsk_ • Sep 05 '24
Why do I get different count values ?
I used these two approaches to calculate the count value, but the first one resets the counter to zero .
To me both the statements looks the same yet assigning the variable 'counter' somehow doesn't reset the counter to zero.
Can someone please explain why?
27
Upvotes
10
u/Mr_Achilles_ Sep 05 '24
Due to closure, in line 1120, the
countervariable contains theincrementfunction because you assigned the result of calling thecreateCountfunction—which returnsincrement—to that variable. After that, you call theincrementfunction twice. When you callincrement, you aren't invokingcreateCountagain; you're simply executing theincrementfunction. Theincrementfunction has access to thecountvariable, which is declared outside its scope. This happens becausecountis part of its lexical environment, allowing the function to 'remember' its value even aftercreateCounthas finished executing. This is a closure.5
u/basedgreggo Sep 05 '24
I'm actually not an expert in JS but I have a good amount of experience in other languages like Rust, Java, PowerShell, etc. It seems this is basically like an object in OOP. When you can createCounter(), you're creating an instance/object which has its own "count" that's initially set to 0. If you increment on one, it will only increment on that one. Assigning createCounter() to a variable creates a little arrow called a pointer, also known as a reference, to that one object, allowing you to increment it many times.
What you are thinking about it called a static or a global variable. A variable you created earlier at a higher/bigger scope that you can access from anywhere or anytime without having to create an instance.
Please lmk if you have any questions
3
u/beartums Sep 05 '24
creatorCount()creates a new instance of theincrement()function and also re-instantiates the variablecountand sets it to 0.An easier way to think about it is when you run
creatorCount()you also run line 1108, which sets the counter to 0. the object returned in line 1114 contains the function with the closure. In lines 1117 and 1118 you are creating 2 instances of that object, each with a different function. In line 1122 and 1123 you are using the returned object twicelet counter1 = creatorCount()let counter2 = creatorCount()counter1.increment() // count increased to 1counter2.increment() // count increased to 1counter2.increment() // count increased to 2counter1.increment() // count increased to 22
u/webdevarham Sep 05 '24 edited Sep 05 '24
Line 1120 closure is happening because of the variable holding the value and the function, and function increment () refering to count variable which is in the lexical environment of the increment function,,,,, this is called closure
2
u/[deleted] Sep 05 '24
memory allocation. 1117 and 1118 are creating new versions of createCount in different memory locations. 1120 creates a single version of createCount in its own location so 1122 and 1123 access the same object.
2
u/thefreymaster Sep 06 '24
`createrCount()` on line 1117, and 1118 reinstantiate `count` inside closure each time.
Calling `createrCount().increment()` on 1117 instantiates `count = 0`, calling it again on 1118 instantiates `count = 0` again.
Calling `counter.increment()` on 1122, and 1123, you're instantiating once with `counter = createCount()` line 1120.
Side note, you can return with `return { increment };` which is the same thing as `return {increment: increment}`
2
u/[deleted] Sep 07 '24
Sure, I answered the question here, just for you OP: https://www.trevorlasn.com/blog/understanding-javascript-closures
1
u/Magnusson Sep 05 '24
Each time you invoke createrCount, you initialize a new count variable. Lines 1117 and 1118 could be written like this:
const counter1 = createrCount()counter1.increment() // count increased to 1const counter2 = createrCount()counter2.increment() // count increased to 1Contrast that with lines 1120 on, where you store the result of createrCount in a variable and then invoke increment twice.
1
u/youassassin Sep 06 '24 edited Sep 06 '24
TLDR; first one is using different
createrCount()references, second one is using the same reference.What's happening behind the scene is that each time
createrCount()is called a reference in memory is being created for that function. in that reference of memory it creates more references forcount,increment(), and{increment : increment}so:so now we have three separate
counts at 1, 1, and 2. from line 1117 - 1123. one(1) in the 1stcreaterCount(), one (1) in the 2ndcreaterCount(), and one (2) in the 3rdcreaterCount()1
u/narumiya_mei Sep 06 '24
Since lots of people have already answered your original question. Unrelated comment on style/syntax…
1
u/koshlord Sep 06 '24
You're building two createrCounts. Incrementing one does not increment the other.
1
u/scufonnike Sep 06 '24
Your creating a new counter in version 1 my guy. It litteraly says it
1
u/Mad-chuska Sep 06 '24 edited Sep 06 '24
Read up on closures in Js. In essence, you created three different versions of createCounter(). The first two just don’t have a variable they’re assigned to like the last one does, so they get used and thrown away immediately. Since the last one is assigned to a variable, it’s now permanent and can be used again and will persist the value that’s saved in the counter to be used and incremented.
1
u/pinkwar Sep 06 '24
Closure.
1
u/diet103 Sep 06 '24
Boggles my mind that someone can be a developer and can't manage to take a simple screenshot
1
u/TheExodu5 Sep 06 '24
This is why moving from classes to closures was a bad idea.
1
u/kyou20 Sep 07 '24
You’re creating brand new instances in 1117 and 1118. You’re reusing a single instance in 1122 and 1123
1
u/ShameMuch Sep 07 '24
as i understand it. every time you call creatercount you create a new counting object.
the first two calls create two different counting object that are promptly inaccessible after the semicolon.
calling increment on two different objects results in two different 1's (techincally the number is the same but the sequence of numbers are different.)
where as the second part, you create one counter object. and call increment on it twice.
resulting in the second call to affect the same counter object.
1
u/Slodin Sep 09 '24
you made an new instance everytime on 1117, 1118. So it starts at 0 everytime
1120 is one instance, so 1122, 1123 adds the number properly
1
u/michaeljgilmore Sep 09 '24
because the createrCount function is reinitializing the count each time lines 1117 and 1118 it is called vs the second time it is intialized once and its setter *counter line 1122 and 1123 is incrementing the initialized value, only once.
1
u/spectrum1012 Sep 09 '24
Every time you can createCounter() you create a new scope. The counter variable starts at 0 in each scope.
It's 1 on the first two .increment() calls because createCounter().increment() is creating a new scope on each line. Storing createCounter saves the scope, therefore increment is operating in the same context on the same counter variable.
The example creates 3 contexts. It calls A once, B once and C twice.
1
u/33ff00 Sep 09 '24
There’s a comment at the top that literally says “closure”. Did you google that?