josh_c
josh_c

Reputation: 149

Javascript Closure / Scope

I am learning about closure and scope, and came across this example. I am confused as to why humansMoney continues to decrement every time the function is invoked, yet it seems to me that it should be reset to 100 on every invocation.

The instructor at one point mentioned that by calling carl(), we are only calling the inner function, not the outer function. I simply do not understand this.... carl() is calling human(), so why would humansMoney not get reset to 100?

Can someone please explain (like I'm 5) why this phenomenon is occurring? I would very much appreciate any advice on this.

Thank you so much.

function human() {
    var humansMoney = 100;

    function cat() {
        humansMoney--;
        console.log('human: ' + humansMoney);
        var catsMoney = 100;
        console.log('cat: ' + catsMoney);
    }
    return cat;
}

var carl = human();

carl(); // humansMoney = 99, catsMoney = 100
carl(); // humansMoney = 98, catsMoney = 100
carl(); // humansMoney = 97, catsMoney = 100
carl(); // humansMoney = 96, catsMoney = 100 

Upvotes: 0

Views: 87

Answers (2)

dmitrydwhite
dmitrydwhite

Reputation: 826

The return value of calling the function human is essentially the definition of the inner function cat, with a closure containing a reference to the variable humansMoney. That's why you can invoke carl like so carl(). Every time you call carl(), you're actually calling cat but with the stored and persisting value of humansMoney being stored from one invocation to the next.

If you were to invoke human again, assigning it to a new variable, for example var jim = human(), you would then have a new closure where humansMoney was 100. Now every time you call jim(), you'll decrement Jim's money.

Upvotes: 0

Quentin
Quentin

Reputation: 944556

var humansMoney = 100; only runs when you call the human function.

You only do that once.

Every other time, you call the carl function, which is the returned cat function.


Re edit.

carl() is calling human()

No, it isn't.

It is calling the value of carl, which is the return value of the expression human(). That's the cat function.

Upvotes: 1

Related Questions