DEV Community

Discussion on: 2 Examples To Help You Understand JS Closures Once And For All 🙃

Collapse
 
devworkssimone profile image
DevWorksSimone • Edited

I dont get in the first example why calling getNextNumber() increase variable count... I thought it would return 1,1,1,1... doesnt calling getNextNumber run createCounter() that set back count everytime to 0 does it?

Collapse
 
harrison_codes profile image
Harrison Reid

Hey! Thanks for reading 😀

What you're expecting would the case if instead of:

const getNextNumber = createCounter()

I'd written:

const getNextNumber = createCounter

However, as the createCounter function is invoked when declaring the const getNextNumber, the return value of createCounter() is assigned to getNextNumber, rather than the function itself.

Since the getNext function is returned from createCounter, it is this function that's assigned to the const getNextNumber.

So when we call getNextNumber(), it is really the getNext function that's being run multiple times, not createCounter, which is only called a single time.

Does that make sense?

Collapse
 
devworkssimone profile image
DevWorksSimone • Edited

Yes, after reading your explanation I get where I was failing. You are assigning getNextNumber variable the getNext() function, not the return of it, or for better day you are assigning the return of createCount() function which is in fact getNext() function. Thanks to pointing that for it to become as I thought, it need to be assined just as createCounter (no brackets) instaed of createCounter(). Hope may help somebody like me who failed to grasp it 😁. Thanks again