Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 896
Fadeoc Khaos Avatar asked Apr 17 '15 07:04

Fadeoc Khaos


2 Answers

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.

like image 193
Benjamin Gruenbaum Avatar answered Oct 14 '22 13:10

Benjamin Gruenbaum


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

like image 44
Sami Kuhmonen Avatar answered Oct 14 '22 14:10

Sami Kuhmonen