0

I have this code (given below) and when I write c1 = count(); I call the function count() (my current understanding), so the closure will memorize c=1 after the first call.

Later, if I call c1() the result is 1. How comes that the result is 1, if when I called this function once by writing c1=count(), c was already incremented to 1? Shouldn't the value be 2?

function count() {
 var c = 0 ;
 return function() {
 c += 1 ;
 return c ;
 };
}

If not,

Why when I write this function, my output is 'A!'? That means that by writing var x=a() I call the function, the same logic should be used in the function above, shouldn't it?

function a() {
 alert('A!');
 return function() {
 alert('B!');
 };
};
var x = a();
Frax
6,0802 gold badges21 silver badges25 bronze badges
asked May 19, 2018 at 11:26
4
  • 1
    "I called this function once by writing: c1=count()" -- no, you didn't. count() and createsreturns an anonymous function that you store in c1 but it doesn't call it. Then you call it using c1(). Commented May 19, 2018 at 11:35
  • I believe he wants to increment a number, but thinks that functions retain some sort of memory Commented May 19, 2018 at 11:35
  • In the second snippet you're just alerting A directly, there's no closure over any variable in a function. Calling x() alerts B. Commented May 19, 2018 at 11:36
  • @DMcCallum83 There is a sort of memory: the variable is stored in closure. Confusion seems to only regard to when function calls happen. Besides, I believe Claire is usually a female name. Commented May 19, 2018 at 11:44

3 Answers 3

4

here is your function,

function count() { 
 var c = 0 ;
 return function() {
 c += 1 ;
 return c ;
 };
}

first time when you call the function count() it does 2 things,

  1. Initialising var c
  2. returns a function which contains a reference to the variable c which was declared in outer scope. (Learn more about closure: This is a good article https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36)

Now return value of count() i.e a return function is assigned to the variable c1. c1 is a function which when you call increments the value of variable c.

when you do,

var c1 = count(); // c = 0 & a function is assigned to c1
c1(); // c + 1 i.e 1
c1(); // c = 2

and so on..

Now next case,

function a() {
 alert('A!');
 return function() {
 alert('B!');
 };
};
var x = a();

when you call a()

  1. alert('A!')
  2. returns a function and assigning it to x;

next time when you call x() it will always alert('B!')

Hope this helps.

answered May 19, 2018 at 11:56
Sign up to request clarification or add additional context in comments.

1 Comment

One more important thing about closures. If you'll assign the result of count for a second time, to another variable, this call will create a new closure, and c1 calls will continue to count c from its current value, i.e. it is not reset.
1

When you call count then you return the inner function from count which you store in c1:

return function() {
 c += 1 ;
 return c ;
};

But at that time you haven't called that returned function, so c is still 0.

When you now call the returned function you stored in c1 by writing c1 then c is incremented by 1, so for the first call of c1 you get 1.

function count() {
 console.log('var c=0')
 var c = 0;
 console.log('return function () { ... }')
 return function() {
 console.log('c += 1')
 c += 1;
 console.log('return c')
 return c;
 };
}
console.log('var c1 = count()')
var c1 = count();
console.log('c1()')
console.log(c1())
console.log('c1()')
console.log(c1())

answered May 19, 2018 at 11:41

4 Comments

What happens when I have only this : c1 = count(); ?
@Claire c=0 and the return of the function you define within count but that function is not called at that time. Check the logs messages of the runnable snippet.
So that means that in the second function if i do : x(), the result will be 'B!' ?
@Claire Well, what does it show if you do so? I mean it would be faster to test that your self then asking it as a question.
-1
function count() {
 var c = 0 ;
 return function() {
 c += 1 ;
 return c ;
 };
}

Every time you call that function, you set the value to 0 - so it's alway going to return one. Instead call it increment count, and pass the value to be incremented in:

function incrementCount(valToInc) {
 return valToInc += 1;
}
incrementCount(4); //returns 5
answered May 19, 2018 at 11:34

1 Comment

No, it won't be always 1. The call of count will return a function and never 1, and if you then call this returned function, it will increment c every time it is called: fiddle demo

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.