Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript executing function that returns function

I have the following two counter functions which return different result when they run.

In the first snippet, counter function is assigned to variable letsCount and it looks like executing the function updates the var count in the counter function.

However in the second snippet, executing the function directly doesn't update the count variable.

Would you please explain why they have different results and what happens when the function that returns function is assigned to a variable?

Snippet 1

function counter() {
    var count = 0;
    return function() {
        console.log(count++);
    }
}
var letsCount = counter();
letsCount();    // 0
letsCount();    // 1
letsCount();    // 2

Snippet 2

function counter() {
    var count = 0;
    return function() {
        console.log(count++);
    }
}
counter()();  // 0
counter()();  // 0
counter()();  // 0
like image 362
Katie S. Avatar asked Apr 27 '26 11:04

Katie S.


1 Answers

Every time you call counter() you create a new anonymous function instance, with its own scoped variables. If you want to keep using the same function, you will have to do something like this :

var counter = (function () {
    var count = 0;

    var fn = function() {
        console.log(count++);
    };

    return function () {
        return fn;
    };
})();

counter()();  // 0
counter()();  // 1
counter()();  // 2

A single anonymous function will be created then stored in a scoped fn function, then we return a function which, when called, will returns the value kept by fn.

like image 89
Maël Nison Avatar answered Apr 29 '26 00:04

Maël Nison