Stop a for loop before reaching a number

I just solved this Fibonacci challenge from Project Euler, but I would like to optimize it so that the loop stops before exceeding the argument n. For example if n is 10, I want the fibs array to be [ 1, 1, 2, 3, 5, 8], but having the if (fibs[i + 2] > n) condition in place makes the loop reach the exceeding value and break after that. Which I guess makes sense, but how do I stop it before it exceeds n?

function fiboEvenSum(n) {
let fibs = [1, 1]
for (let i = 0; i <= n; i++) {
  fibs[i + 2] = fibs[i] + fibs[i + 1]
  if (fibs[i + 2] > n) {
      break
  }
}
console.log(fibs)
  return fibs.filter(a => a % 2 === 0 && a <= n).reduce((a, b) => a + b)
}

I’m not sure I understand this question. Don’t you want to keep going while it is less than/equal to n. Why would you want to stop before then?

A for loop executes n times. You are looking for a different sort of loop. What about a while?

1 Like

I see, it’s just that I need the for loop to create the sequence. But oh well, it’s still passable as it is.

So that I can get rid of this condition in the filter() xD

No, you don’t. You can use a while loop to create the sequence instead. breaking early on purpose is an indication that you are using the wrong type of loop.

You also don’t need an array of the Fibs, but that’s a more extensive update.

The only way I can think of using while is declaring 3 variables. Are you hinting at using reduce() when you say there’s no need for an array?

There are a few ways to use a while loop.

You need an array if you want to use reduce. There is a way to use zero arrays.

FYI
Fibs have a bunch of interesting properties and patterns, some of them can be used here in this challenge to end up with somewhat fancy solution.

For example, starting with 2, every third fib number is even. Maybe you’ll find a way to use it here.