Ben
Ben

Reputation: 489

Strange solution for fibonacci, explanation needed

My first implementation of the fibonacci algorithm was:

function fibo(max, old = 0, curr = 1) {
  if( old === 0 && curr === 1 ) { console.log(curr) }
  if(curr + old < max) {
    console.log( curr + old);
    fibo(max, curr, old + curr);
  }
}

fibo(50);

I was playing with the fibonacci algorithm in javascript and I stumbled upon a strange but neater solution that I can't explain:

function fibo(max, old = 0, curr = old++) {
  if(curr + old < max) {
    console.log( curr + old);
    fibo(max, curr, old + curr);
  }
}

fibo(50);

why does this function display 1 1 2 .. and not 1 2 3 ... ?

Upvotes: 0

Views: 56

Answers (1)

user9274775
user9274775

Reputation:

why does this function display 1 1 2 .. and not 1 2 3 ... ?

old is 0 until it gets to the initialization of the default parameter (on the first invocation), which increments it to 1 and sets the original value of old to curr.

So old is 1 and curr is 0 on the first call, and 1+0 is 1 for the first call, and then it will be 1+0 for the next call.

This is a little confusing, because on the first call, the old ends up being behind the curr, but the sum is of course the same.

Upvotes: 3

Related Questions