Recursion help needed

I have this piece of code below, a function that gives us the first n Fibonacci numbers.

However, even after trying to substitute, I cannot understand what is happening at the ‘else’ part of the function.

Could anyone explain it please?

function fibonacci(n) {
  if (n === 1) {
    return [0,1];
  } else {
    var counter = fibonacci(n - 1);
    counter.push(counter[counter.length - 1] + counter[counter.length - 2]);
    return counter;
  }
}
console.log(fibonacci(10));

Welcome, D4.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

Also, here is a potentially useful discussion on the topic of recursion: Replace Loops using Recursion -1 explanation

Hope this helps

Hello Sky020,

Thanks for your quick response, I’ll be careful with the markdown next time!

I have read the thread that you provided and it is all clear for me (it might have been an easier example), but I still struggle to understand what is happening here exactly in this particular case.

counter[counter.length - 1] is the n - 1st element and counter[counter.length - 2] is the n - 2nd element.

My guess of what I do not understand is, how does var counter work after we assign fibonacci(n - 1) to it.

Where is the result sequence stored until we get to the ‘n’-th element?

fibonacci() returns an array.
var counter = fibonancci(n-1) will be an array.
The next line pushes another value to the array.
Then that array is returned.