Steven L.
Steven L.

Reputation: 2155

Why does count++ not work when being passed as an argument

I have the code below. If you pass the code a list, it will provide the value in that position (it is zero-indexed). This code works, but if I replace count = count + 1 with count++ (in the last branch on the conditional), it no longer works. Can someone help me understand why?

Note: If you call the function like this:

var list = {value: 10, rest: {value: 10, rest: {value: 30, rest: null}}}

nth(list, 1)

The output should be 20.

function nth(list, index, count) {
    if (count === undefined) {
        count = 0;
    }

    if (count === index) {
        return list.value;
    }
    else if (list.rest === null) {
        return undefined;
    }
    else {
        // note that count++ will not work here
        return nth(list.rest, index, count = count + 1);
    }
}

Upvotes: 0

Views: 147

Answers (2)

user4628565
user4628565

Reputation:

try to change,

return nth(list.rest, index, count = count + 1);

to

return nth(list.rest, index, ++count);

Upvotes: 0

user133688
user133688

Reputation: 7064

This is because

 count++

Is a postfix increment. That means it creates a new value, the old count, and passes that value into the function.

You want prefix.

 ++count.

Upvotes: 8

Related Questions