Katie S.
Katie S.

Reputation: 85

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

Upvotes: 3

Views: 415

Answers (4)

David G
David G

Reputation: 96800

It actually makes perfect sense why you're getting that behavior. When you call counter()(), the first counter() call is executed, effectively resetting the variable count to 0. When you set a variable to counter(), you are actually setting it to the returned function:

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

// })();

Then when you call letsCount, you're calling the returned function and not the outer function.

Upvotes: 0

alex
alex

Reputation: 490153

Snippet 1 and Snippet 2 differ in their invocation. Your first snippet has a reference to the one returned function, and that function holds onto its scope (is a closure, has a reference to count).

Your second snippet calls the outer function each time, always returning a reference to a new function, with a new closure to a fresh count.

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

In the first case you are referencing it with a function pointer.. So the context is saved

Whereas in the second case you are calling the function , wherin the count is 0 . So the variable is out of context in here,, So you see the value as 0

Upvotes: 0

Maël Nison
Maël Nison

Reputation: 7353

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.

Upvotes: 2

Related Questions