Falsy Bouncer 01010101

When I remove all false values it returns an array with an extra comma. [7, ate, , 9].

Your code so far

function bouncer(arr) {
  // Don't show a false ID to this bouncer.

let newArr = arr.filter(item => item !== false);


  return newArr;

bouncer([7, "ate", "", false, 9]);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36.

Link to the challenge:

When I run that code, I don’t get an empty field like that, it has an empty string. This is a problem because an empty string is falsy.

The problem is here: !== false.

Falsy and false and truthy and true are not always the same thing. Part of the problem is that you are using the “strictly no equal” operator, but even with the looser not equals, we get:

console.log(('' != false)); // false
console.log((null != false)); // true
console.log((undefined != false)); // true
console.log((NaN != false)); // true
console.log((0 != false)); // false
console.log((false != false)); // false

Not what we expect.

One sure fire way to turn a falsy value into a true “true” is the “not” operator. As in !null != false evaluates to true. If we want, we can do the “not” operator twice and flip it 360 degrees: !!null != false evaluates to false. Yes, it’s weird, but the double not operator is a great and dependable way to convert a falsy value into a false value (and the same for truthy and true). It looks weird, but it is fairly common.

So, for this code, you could just apply a double not to item - that would convert it to true or false. That works. Of course, it’s kind of silly to see if a boolean value is not equal to false - that’s the same value as the boolean value itself. So in that case, you don’t need the !== false. In fact, since item evaluates as truthy or falsy, we don’t even really need to convert it to a true boolean - this works if we just return item.

But personally I prefer the second option, with the double not (!). If I see that, I know exactly what is happening - truthy and falsy values are being converted to true and false. I think that’s clearer and faster to read - once you’re used to seeing it.

1 Like