Understanding process of variable updates with loop

This returns an error of “Unexpected token ‘sumFibs(num) {.’”
An array with two values is set. The formula for each term is provided. While terms are less than or equal to argument, and odd, add them to the sequence. Find the sum of each term with a collector called sum. Return sum. The problem could be in the if statement or the braces. Does something not make sense?

sumFibs(num) {
  let sequence = [0,1];
  let term = sequence[sequence.length - 1] + sequence[sequence.length - 2];
  let sum = 0;
  while (term <= num)  {
    if (term % 2) {
      sequence.push(term);
      sum += term;
    }
  }
  return sum;
}
sumFibs(7);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Edg/88.0.705.63.

Challenge: Sum All Odd Fibonacci Numbers

Link to the challenge:

You just need to stick function in front of sumFibs so JS knows you are declaring a function.

1 Like

Yes that’s what I did and the function works, but it doesn’t return nothing but at least it doesn’t show any errors :>

function sumFibs(num) { ...

Thanks, bbsmooth. My belief is suspended.

now it seems you have an infinite loop as term and num never change

I am not sure how to change num and sum. sum = sumthing and num = aNewNum to nowhere.

Your while loop condition is causing you some issues:

while (term <= num)  

The value of either term or num has to change inside of the loop or it will just keep looping forever (which is what is happening here).

Instead of trying to do everything that needs to be done in one while loop I think you should break this into steps and concentrate on each step one at a time. I see three basic steps here. I’ll get you started:

Step 1: Fill an array with all of the Fib numbers <=num.

I’ll let you figure out steps 2 and 3.

Once you get a working function then you can go back and refactor to make your code more concise if you wish.

1 Like

Some parts have been taken out of the while loop. The first step is making an array of odd values. The next was making a sum of those chosen numbers.

function sumFibs(num) {
  let sequence = [1,1];
  let sum = 0;
  let term = sequence[sequence.length - 1] + sequence[sequence.length - 2];
  while (term <= num)  {
    sequence.push(term);
    term = sequence[sequence.length - 1] + sequence[sequence.length - 2];
  }
  let oddSequence = sequence.filter(element =>  {
   return ( element % 2);
  });
  let sumOfOdd = oddSequence.reduce((accumulator, currentValue) =>  {
    return accumulator += currentValue;
  });
  return sumOfOdd; 
}
sumFibs(8);

Thank you for your pointers and assistance. I was growing irritated with all the hitches.