2

I am new to JavaScript (and StackOverflow) and am hoping to get some help on a problem that has bothered me for some time. I understand that functions are considered objects in JS. A function is different from an object in the sense that it can execute code.

This may be a very simple and straightforward question to some of you veteran folks. I don't understand how the code works below. Essentially there is a function count() that returns an anonymous counter function. keepCount points to the anonymous function (an object, of course) that count() returns.

function count() {
    var num = 0;
    return function(correct) {
        if (correct)
            num++;
        return num;
    } 
}

var keepCount = count(); 
keepCount(true); // num is 1 
keepCount(true); // num is 2
keepCount(true); // 3
keepCount(true); // 4
console.log(keepCount(true)); // Call it again and print. It is 5. 

My question: What is causing the result of num to be 'saved' or recorded with each function call? Isn't num a variable local to count() — the outer function? num does not appear to be a property of the anonymous function. I suspect the answer has something to do with the fact that functions are considered objects in JS, and that a local variable can be continuously updated in the variable object of count(). A new variable object is not produced for count() with each call of the anonymous function.

I would also appreciate comments on the formatting of this question and all. I want to be sure that I am following StackOverflow guidelines properly. I also hope that the details of the question make sense. Please let me know if anyone requires clarification.

Nithish
  • 5,393
  • 2
  • 9
  • 24
  • PLease check once the concept of closures. That will help you understand this . For ref https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4 – Harmandeep Singh Kalsi Jul 04 '20 at 16:06

0 Answers0