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

thank you for your time.

I studied the Fibonacci function, and one of the answers 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)) 

Since .callee arguments are forbidden in strict mode after ES5, I replace it with a function name. After that, I saw part i + 1, and I replaced it with i ++, which turned out to be 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 several debugs, I found out that I + 1 works fine, while I ++ do not.

So, did I use ++ the wrong place, or didn’t I understand ++ at all?

Thnx again.

+6
source share
3 answers

i+1 means "return value that is greater than i, do not change i"

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

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

So, in this case, if you use i+1 , you do not change the value of i, but you send a value greater than i as an argument. You can also use ++i if you also need to change the value in i.

<strong> 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 to i-1 , i-- and --i

+6
source

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

This means that you skip i everywhere, not i + 1 .

It’s better to just pass i + 1 , as this value will be requested - but ++i .

+10
source

This is because only the output of i++ matches the output of i + 1 .

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

So

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

Source: https://habr.com/ru/post/985327/


All Articles