Javascript Novice to Ninja Chapter 11 Closure Example

Hey everyone, just had a quick question about the closure example given in Novice to Ninja Chapter 11 the Closure example. Just having trouble wrapping my head around this one, was hoping someone could explain why this occurs.

The example given is this:

function counter(start) {
i = start;
return function () {
return i++;
}
}

var count = counter(1);
count();
<< 1

count();
<< 2

My question here is that when you call count() the first time, why is it returning a 1, when the function inside of it, is telling it to increase itself by one. So shouldn’t the first output be 2 instead of 1, I did this in the browser as well to test it out and it came out with the same result as the book, so what I am asking is why does it return 1 the first time if the function is asking it to increment itself by 1, so thus, shouldn’t it be 2? Thank you for the help.

This statement says to return i first and then add 1 to i.

To have it add 1 first and then return the result you’d use ++i instead

Thank you so much felgall, that explains everything. Your awesome. Thanks again.

It’s the i++ that is causing the confusion. How that works is to give the value of i, and only after giving that value does it increase it.

Another way to write that without the confusing i++ is:

function counter(start) {
    var i = start;
    return function () {
        var temp = i;
        i += 1;
        return temp;
    }
}

[edit]
I really should scroll down before replying :slight_smile:
[\edit]

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.