Falsy Bouncer - code returning various amounts of "null"

Falsy Bouncer - code returning various amounts of "null"
0.0 0

#1

I tried solving this through a filter function that would iterate over a list of the “falsy” arguments and return false or true depending on if the array value matched any of the words.

Edit: Disclaimer, I solved it later using the correct way. Just curious why this doesn’t work.

function bouncer(arr) {
    return arr.filter(function falsy(toFilter) {
    var testVal = [false, null, 0, NaN, undefined, ""];
     for (i = 0; i < testVal.length; i++){
       if (toFilter === testVal[i]){
         return false;
       }
     }
     return true;
  });     
}

It worked for the first two tests but
bouncer([false, null, 0, NaN, undefined, ""]);
returned [null]
and

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

returned [1, null, 2]

why is this?


#2

I think you meant bouncer([false, null, 0, NaN, undefined, “”]); returned [ NaN ] and bouncer([1, null, NaN, 2, undefined]) returned [ 1, NaN, 2 ].

The reason the NaN is still in the array is because when you compare the equality of any value to NaN it will always be false. NaN is not a specific value so even if you write NaN === NaN it will still be false. Read more about NaN in the documentation.


#3

Thanks @randelldawson , will read up on that!
It might be the sites output that converts NaN to null.
But this is the return i get from

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


#4

That is the “fake” console. Go to the real console (Ctrl+Shft+J in Chrome) and see what is actually being returned. You may need to write it as console.log(bouncer([1, null, NaN, 2, undefined])); to see there.


#5

You are correct. Thank you for the explanation!