+ 4

Closure. Why does it work ?

Hello everyone I have a problems with understanding of closures. This is counter with closure. function makeCounter() { let count = 0; return function (){ return count++; }; } let counter = makeCounter(); alert(counter()); //0 alert(counter()); //1 alert(counter()); //2 So why does it work? Why every time when we invoke counter the count variable changes ? I’ve tried to make it without closure. function makeCounter(){ let count = 0; return count++; } alert(makeCounter()); //0 alert(makeCounter()); //0 alert(makeCounter()); //0 Why this code doesn’t work the same way as code with closure ??? Please help me. I really need to figure out how does it work.

6th Jun 2019, 9:03 AM
max
max - avatar
26 Respostas
+ 8
David Carroll there was no reason to remove your comments, it was a nice polite discussion, no insults. I demonstrated my arguments (although initially exposed in a bad way) providing reliable reference. Now I'm aware I have to work hard on my exposition skills(and improve my English) if I want to give an appreciable help to the community. I realized that a bad exposition results in confusing rather than helping! This is a true lesson for me and I would say thank you! It's been two years since I've started learning programming and I remember now how it was hard to understand almost everything at the beginning. Now I am more aware than ever that help people isn't an easy task! Best regards.
10th Jun 2019, 12:09 PM
AZTECCO
AZTECCO - avatar
+ 8
Idk.. now it doesn't seem to be useful to resume this discussion which may seem a dispute although somebody found it funny(just kidding). I'm glad we met each other, and I understand your intentions, maybe my difficulties in explaining didn't helped. Also if you feel the same it's better I leave my inappropriate and useless comments. I'm gonna remove some and edit to save what I hope is good for the community. Again I'm glad we met each other and this is a good example to all we should be proud of.
10th Jun 2019, 7:42 PM
AZTECCO
AZTECCO - avatar
+ 6
Closures aren't magic. They are functions which return a function as in your example. See, in this line: let counter = makeCounter(); you're calling the makeCounter. First, it declares count = 0, then it return an anonymous function which gets assigned to counter variable. So, now counter is a function. Therefore when you call it inside alert, it "first returns count, and then increments it". Note that this doesn't mean that count is global. Only, the scope of count is preserved in the counter function. While in the second one, the count is declared everytime as 0.
6th Jun 2019, 9:17 AM
777
777 - avatar
+ 6
It appears.. it appears a lot! Hope you take more care of me in the future. I hate that, I have a good opinion of you, and I esteem your experience. I put my efforts to help people understand or at least put them in the right way, I can make mistakes, sure, I can explain better, sure, but the way you treated me seems more like a humiliation to me. We should meet us instead.
9th Jun 2019, 7:38 PM
AZTECCO
AZTECCO - avatar
+ 6
Robin R. Let me know if you would like to explore this concept further offline. I think I've over stayed my welcome on this thread. 😉 Apologies max for the distraction cause by my earlier posts.
9th Jun 2019, 10:54 PM
David Carroll
David Carroll - avatar
+ 6
AZTECCO I truly am glad you feel this way. I do always try to conduct myself as respectful and kind to others as much as possible. 😉 I also try to be mindful of how English isn't everyone's first or even second language in this global community. I wouldn't be able to communicate a fraction of your ability in another language. I hope to continue engaging with you on various technical topics. There's always new things to learn and contribute. ---- Regarding My Deleted Answers: ---- Again, I felt horrible that my original comments gave the impression that I was trying to embarrass you with such a scrutinized breakdown of what I thought was wrong. While that wasn't my intention, I now see how it could be perceived to be the case. If you feel my deleted comments are still worth sharing, I do have a clone of this discussion with the original, unedited text, as it existed, prior to me deleting my answers. You can DM me for a link or I can post that here for full transparency with the community.
10th Jun 2019, 7:10 PM
David Carroll
David Carroll - avatar
+ 5
Because in closure, makeCounter() only run once, let counter set to 0 only once. Later counter() ia called would only run the callback function to increment the count. However in makeCounter() function, everytime the function is called let counter set to zero.
6th Jun 2019, 9:20 AM
Calviղ
Calviղ - avatar
+ 5
Lol sorry Robin R. I'm sure you'll come back soon and explain it right!
9th Jun 2019, 7:46 PM
AZTECCO
AZTECCO - avatar
+ 5
AZTECCO Every once and a while, I'll come across a profoundly interesting comment that truly piques my interest, especially when it runs counter to my understanding of conventional wisdom. I find these to be quite intriguing as I'm quite often known to go against the status quo myself. The comment about that ninja article certainly caught my attention, which triggered my initial inquiry for additional context. What followed was an attempt for me to engage in a friendly dialog designed to explore a technical topic I've become quite familiar with over the years. However, for various reasons, I completely failed in my approach, which I believe was made worse the more I tried to respond. Ultimately, my good intentions and genuine desire to enlighten was poorly executed resulting in the opposite effect. While this might work well over voice calls, it fails miserably on this medium. This left you feeling attacked, an outcome I genuinely regret and apologize for. All of my comments have been removed.
9th Jun 2019, 10:52 PM
David Carroll
David Carroll - avatar
+ 4
Robin R. In fact it is clear! This code is a demonstration of the fact that in js functions are objects, and the definition of closure or Functor is function object. Scope is used to achieve class behaviour, js has no classes. Everything you return becomes the public interface , the rest is private internal encapsulated stuffs. Try to return an object.. return{ attempts_count : attempts, reset : function (){attempts=0;}, .... } you got a class with public members.
7th Jun 2019, 8:40 AM
AZTECCO
AZTECCO - avatar
+ 4
Anyway it's good if it helped you at early stages, but if you want to progress it's really important to distinguish these concepts, that way you will combine them better in the future and achieve great things!
7th Jun 2019, 9:05 AM
AZTECCO
AZTECCO - avatar
+ 4
Sorry for the delay Robin R. Fallen asleep ! 😴 zzZ https://code.sololearn.com/WjhtA7qHYPqg/?ref=app
7th Jun 2019, 3:13 PM
AZTECCO
AZTECCO - avatar
+ 4
Compare example 2. In the article .. and MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures You will see that example 2 in ninja article is an example of lexical scoping and not a closure. MDN explain what is a closure after.. The subtle difference is that the function is returned.. Because in js a function is an object ad forms a closure. [At first glance, it may seem unintuitive that this code still works. In some programming languages, the local variables within a function exist only for the duration of that function's execution. Once makeFunc() has finished executing, you might expect that the name variable would no longer be accessible. However, because the code still works as expected, this is obviously not the case in JavaScript.]MDN
9th Jun 2019, 4:23 PM
AZTECCO
AZTECCO - avatar
+ 4
1 A closure is the combination of a function and the lexical environment within which that function was declared. 2 Js has "first class functions", you make closures in js and ok this language applies in a very natural way. A closure is not an anonymous function , but it's made by returning an anonymous function. You can return a named function but it becomes anonymous outside his lexical context. We can return a parametrized functions as closures and make partial applications or function factories.
9th Jun 2019, 7:16 PM
AZTECCO
AZTECCO - avatar
+ 3
Robin R. Sorry to contradict you but it isn't a good article, it is misleading! Scope visibility policy is a different thing, a closure is a function object(put extremely simply)which doesn't have to be consumed immediately but can be executed later, and several times.
7th Jun 2019, 8:17 AM
AZTECCO
AZTECCO - avatar
+ 3
A different example would be.. let saveState = function (myParam,value){ return function (){ document.style...myparam = value; }; } let originalOpacity = new savestate("opacity",document....getOpacity); let saveMargin("margin",document.style.... ...then we change styles in some way... ... and then we reset originalOpacity(); Sorry if this is not a real code but I hope i
7th Jun 2019, 8:56 AM
AZTECCO
AZTECCO - avatar
+ 1
ok. I almost got it. But can we make a counter without closure ? it will help a lot to me to understand why we have to use closure
6th Jun 2019, 9:32 AM
max
max - avatar
+ 1
Sure @max! But, then you will have to declare "count" as public, which means that any function can change it. While with closures, the scope is limited only to the counter function ;)
7th Jun 2019, 2:45 AM
777
777 - avatar
+ 1
Hey max read this, I helped me understand what it is. Didn't even know what it was before. I think David Carroll shared this. http://ngninja.com/posts/javascript-closures-made-super-easy
7th Jun 2019, 8:03 AM
Robin R.
Robin R. - avatar