Sum All Odd Fibonacci Numbers - weird errors

Sum All Odd Fibonacci Numbers - weird errors
0

#1

This is my solution to the problem. It works, but I have a small red box telling me that I should compare with !== and add a semicolon. However, the code with !== does not seem to work, and I can’t find where I should put a semicolon.
Despite of these things, the challenge passes all tests perfectly.

function sumFibs(num) {
  var allFibs = [1,1], oddFibs = [], result = 0;
  
  // creating array with all Fibonacci numbers
  for (var i = 1; allFibs[i] < num; i++) {
    allFibs.push(allFibs[i] + allFibs[i-1]);   
  }
  
  if (allFibs[allFibs.length-1] > num) {
    allFibs.pop();
  }
  
  // function for odd numbers
  function oddNums(num) {
      if (num % 2 !== 0) {
        return num;
      }
  }
  
  // filtering out the odd numbers
  for (var j = 0; j < allFibs.length; j++) {
    oddFibs = allFibs.map(oddNums).filter(function(n) {return n != null});
  }
  
  // summing the odd numbers
  for (var k = 0; k < oddFibs.length; k++) {
    result += oddFibs[k];
  }
  
  return result;
}

#2

I would guess here:

return n !== null;

And by the way:


#3

As @jenovs pointed out, the problem is exactly here:

// filtering out the odd numbers
  for (var j = 0; j < allFibs.length; j++) {
    oddFibs = allFibs.map(oddNums).filter(function(n) {return n != null});
  }

and, in particular, the part n != null. Of course, the code works but only because you got lucky. Here is the why:

That line should actually be n !== undefined because the values you want to filter out are undefined and not strictly speaking null. Why? Because that is how your oddNums(num) function works:

// function for odd numbers
  function oddNums(num) {
      if (num % 2 !== 0) {
        return num;
      }
  }

Since your function does not handle the case when num is even with an else clause, the function returns undefined whenever it gets an even number. If you don’t believe me, copy-paste this code into your browser console:

[1, 2, 3, 4].map(// function for odd numbers
  function oddNums(num) {
      if (num % 2 !== 0) {
        return num;
      }
  }) // returns [1, undefined, 3, undefined] on Chrome

You got lucky because JavaScript converts values during non-strict equals/unequals checking and undefined != null evaluates to false as you would want. However, in the case of strict non-equals checking, values are not converted. So undefined !== null evaluates to true meaning your code fails to filter the undefineds.