Falsy Bouncer(0)

Tell us what’s happening:
I’m making a function that filters out all array values that are 0, null, false, NaN, undefined, and “”. I don’t know what I’ve done wrong here.

Your code so far

function bouncer(arr) 
  var newArr = arr.filter(function(arr){ return arr != false && arr != NaN && arr != undefined;});
  return newArr;

bouncer([1, null, NaN, 2, undefined]);

Your browser information:

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

Link to the challenge:

You can’t check NaN for equality with == or ===, because NaN === NaN evaluates to false (weird, I know).

You can check if value x is NaN using either of these (among others):

x !== x; // because NaN === NaN is false
// or

Also, there’s actually a much simpler solution to this challenge. See this quote from the MDN article on .filter():

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true.

“Coerces to true” is another way of saying “is truthy”, which is another way of saying “is not falsy”.

Note that the first value passed into the .filter() function is actually the specific element of the array being iterated over, not the whole array, so it would make more sense to name it el or val rather than arr.


[0, 2, 4, 6].filter(function(el) {
  return el > 3;
>>> [4, 6]

Edit: Link to .filter() article was broken, now fixed.