GLPease
GLPease

Reputation: 591

Javascript i++ too much recursion, i+1 ok in tail recursion

thanks for your time.

I was learning an Fibonacci function and one of the answer is below:

function fibonacci(n) {
    return (function(a, b, i) {
        return (i < n) ? arguments.callee(b, a + b, i + 1) : a;
    })(1, 1, 1);
}
console.log(fibonacci(51))

As the arguments.callee is forbidden in strict mode after ES5, so I replace it with a function name. After which, I saw the i + 1 part, and I replace it with an i++, which turns out too much recursion.

function x(n){
    return (function y(a, b, i){
        return (i < n) ? y(b, a + b, i++) : a;
    })(1,1,1)
}
console.log(x(51))

After a few debug, I found out that the i + 1 works fine, while i++ does not.

So, did I use i++ the wrong place or I havent understood i++ at all?

Thnx again.

Upvotes: 6

Views: 177

Answers (3)

Ron van der Heijden
Ron van der Heijden

Reputation: 15070

This is because only the output of i++ is the same as i + 1.

But when you use i++ you also assign the value to i.

so

var i = 0;
output i++; // 1
output i; // still 1

var i = 0;
output i + 1; // 1
output i; // 0

Upvotes: 4

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31153

i+1 means "return value that is one larger than i, don't change i"

i++ means "increment i by one, but return the original value"

++i means "increment i by one and return the incremented value"

So in this case if you use i+1 you're not changing the value of i, but you're sending a value one larger than i as an argument. You could also use the ++i, if you would need the value in i to change also.

Examples

i = 10
a = i+1
// a = 11, i = 10

i = 10
a = i++
// a = 10, i = 11

i = 10
a = ++i
// a = 11, i = 11

The same applies also for i-1, i-- and --i

Upvotes: 6

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

i++ increments a number and returns the old value.

This means effectively that you're passing i everywhere instead of i + 1.

It's better to just pass i + 1 since that's the value you're asking for - but ++i will also work.

Upvotes: 10

Related Questions