Falsy Bouncer Code Explanation

Falsy Bouncer Code Explanation
0.0 0

#1

Hello,

I found the solution of Falsy Bouncer challenge but I don’t know how the code works. The code is simple. Below is the one given in the hint.

function bouncer(arr) {
  return arr.filter(Boolean);
}

Below is the one I found it myself but I don’t how it works too because I was just testing at that time.

function bouncer(arr) {
  return arr.filter(function(x){ return x; });
}

Could someone explain clearly how the 2 snippet code above works? For the second, why the falsy values are removed through the filter method even in the filter’s callback function there is no test case (just return x)?

Thank you.


#2

Something like this:

  • The function takes an argument called arr
  • then it returns the result of a filter applied to each element of the array
  • the result is returned as one array
  • the filter only returns items that are true
  • the filter checks the value of the item, lets say we have the array [7, "ate", "", false, 9] to check
  • 7 is a number, but a number is not a Boolean. Hmm, we can’t compare apples to oranges, so let’ see what 7 is as a Boolean, because that is what we are interested in. 7 as a Boolean is true - oh, cool, since it is true we’ll add it to the result array.
  • ate is a non-empty string = boolean true as well
  • "" is an empty string = boolean false here, let’s drop this from the result array
  • false is , well, false. It will not be in the final array becasue, uhmm, it is false
  • 9 is like 7 = true, the only number that is false is a 0 anyway

That is more or less how it goes.

ps. Javascript temporary makes items the same type for comparisons, so if you compare "1" == 1 the result would be true. If you want to be very specific and tell Javascript to not convert the types you would have to use === as operator, but this is only really necessary in a very small number of cases, since most of the time type casting saves you a lot of work.


#3

This is called coercion and there is a great explanation in the YDKJS series here.

Actually, when you make the comparison of “adsadads” == 1 OR “adsadads” === 1, both of these evaluate to false.

I think @lukaszsobek was trying to show how “2” == 2 evaluates to true while “2” === 2 evaluates to false.


#4

Thanks for the help :slight_smile: Edited