Falsy Bouncer - Only covers half the cases

Falsy Bouncer - Only covers half the cases
0

#1

Hi,

I checked out the solutions on this one finally. However I am not sure why the code below doesn’t work. Or ‘return val != Boolean()’ seems to work only for the first half of “” cases. Why are the other cases NaN, etc, omitted under this interpretation ?

Your code so far

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  var filteredArray = arr.filter(isFalse);     
  console.log(filteredArray);
  return filteredArray;                               
}

function isFalse(val) {
  return val != Boolean();
}

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

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:


#2

You got lucky on the other test cases. The above code’s return statement is testing whether val is not equal to false, because Boolean() evaluates to false. so in the following test case:

bouncer([false, null, 0, NaN, undefined, “”]);
1st iteration - val = false and Boolean() = false, so false is not included
2nd iteration - val = null and Boolean() = false, so null is included because they are not equal
3rd iteration - val = NaN and Boolean() = false, so NaN is included because they are not equal
4th iteration - val = undefined and Boolean() = false, so undefined is included because they are not equal


#3

Ah, okay. For one I see the tautological error there, thanks for pointing that out. Obviously ‘!=’ would not be the appropriate operator there-- However, even with this logic, using even standard equality ‘==’ or strict ‘===’, should pass those cases, no ? But that doesn’t work either.

I believe this is the right term, but it is the ‘functional’ nature of commands like filter that I am still trying to wrap my head around as this style of programming is new to me.

Thanks for your help Randell.


#4

filter expects a true or false value to be returned from the function passed to it. If you return something other than true or false, it will still evaluate whatever is returned as true or false. As mentioned in the challenge, the values false, 0 (zero), ‘’ or “” (empty strings), null, undefined, NaN are falsy values and everything else is truthy, so just returning each array element’s value will evaluate correctly. See if you can modify the function used in the filter callback using this knowledge. Once you figure it out, you see how simple and elegant the solution can be.

Here is a simple function which demonstrates how truthy and falsy values are evaluated:

function trueOrFalse(value) {
  if (value) {
    console.log(value + ' evaluates to true')
  }
  else {
    console.log(value + ' evaluates to false')
  }
}
trueOrFalse(3); // 3 evaluates to true;
trueOrFalse(undefined); // undefined evaluates to false;