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?
What you're expecting would the case if instead of:
constgetNextNumber=createCounter()
I'd written:
constgetNextNumber=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.
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
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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?
Hey! Thanks for reading 😀
What you're expecting would the case if instead of:
I'd written:
However, as the
createCounter
function is invoked when declaring the constgetNextNumber
, the return value ofcreateCounter()
is assigned togetNextNumber
, rather than the function itself.Since the
getNext
function is returned fromcreateCounter
, it is this function that's assigned to the constgetNextNumber
.So when we call
getNextNumber()
, it is really thegetNext
function that's being run multiple times, notcreateCounter
, which is only called a single time.Does that make sense?
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