Why do I return undefined for a large number but not a small one? (Fibonacci Sequence Sum)

Viewed 43

this code right here does work, but i don't quite understand why.

if i remove the interior return statement and keep only the one at the end, it will return the correct sum (44) for console.log(evenFibonnacisSum(100)), but undefined for console.log(evenFibonnacisSum(4000000)).

if i remove the exterior return statement and keep the one inside the if statement, it will return undefined for console.log(evenFibonnacisSum(100)) but the correct sum (46000000 or so) for console.log(evenFibonnacisSum(4000000)).


function evenFibonnacisSum(upperlimit){
  let evenSum = 0  
  let seq = [0, 1]
  for(i=0; i<=upperlimit; i++) {
    if(evenSum<upperlimit) {
      let next = seq[i]+seq[i+1];
      seq.push(next)
      if(seq[i]%2 === 0 && seq[i]<upperlimit) {
        evenSum += seq[i]
       }
    } else {      
      return evenSum
    }
  }
  return evenSum
}

console.log(evenFibonnacisSum(100))

console.log(evenFibonnacisSum(4000000))

it's not a huge problem, but it's really unintuitive. anyone have any insight into why this might be?

1 Answers

If you remove the interior return and pass in a large upperlimit, then it will attempt to execute the loop too many times. Your environment realizes that it is taking too long and aborts the function.

If you remove the external return then for 100 you never hit the interior return because the correct answer has evenSum < upperlimit.

I would suggest coding it like this instead:

function evenFibonnacisSum(upperlimit){
  let evenSum = 0
  let seq = [0, 1]
  i = 0  
  while(seq[i] < upperlimit) {
    let next = seq[i]+seq[i+1];
    seq.push(next)
    if(seq[i]%2 === 0) {
      evenSum += seq[i]
    } 
    i++
  }
  return evenSum
}
Related