Why the code is not giving desired result?

Tell us what’s happening:
Describe your issue in detail here.

So I want to print first n fibonacci numbers when i run the function fib(n). But in the output, it is returning the nth number twice even though i have provided the condition of i < num in the code below. Example if i run fib(5), the output comes as “1 1 2 3 5 5”.

  **Your code so far**

function fib(num) {
let arr = [1,1];
for(let i=2; i<num; i++){
  arr[i] = arr[i-1] + arr[i-2];
return arr.join(" ");

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0

Challenge: Sum All Odd Fibonacci Numbers

Link to the challenge:

Why are you adding the nth Fib number twice?

1 Like

Sorry didn’t get you here. Can you please elaborate. Has it something to do with my formula for arr[i] ?

This puts the ith Fib number into your array.

This puts the ith Fib number into your array again.

You are using two syntax that both add to your array.

Oh got you. So basically the output of arr[i] = arr[i-1] + arr[i-2]; automatically gets inserted in the arr. I was of the view that once the result comes, it has to be pushed in the chosen array.

Right, that syntax literally says to set the contents of the array at index i

Got it. Thanks a lot mate. :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.