Falsy Bouncer - Why is this even working?


#1

I just started a new challenge called Falsy Bouncer and started by filtering through the array with the normal filter function.

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  return arr.filter(function(x) {
    return x;
  });
}

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

Then I realized that with this function I already mastered this challenge. Just one question remains: why?


#2

It doesn’t work because your filter() function does do nothing but returning every element. In this exercise you should filter out any FALSY element like in solution below

function bouncer(arr) {
    // Don't show a false ID to this bouncer.
    return arr.filter(Boolean);
}

#3

It works because that is the definition of falsy - the filter callback return is boolean - from MDN

A falsy value is a value that translates to false when evaluated in a Boolean context

When the callback simply returns the element of the array the returned value of the callback is evaluated in a boolean context by filter to determine if the element should be kept or dropped - all returned falsy elements are evaluated as false by filter and dropped - all returned non-falsy (truthy) elements are evaluated as true by filter and kept


Explain to me my own code pls )
#4

No, the weird thing is that it is indeed working.

That’s why I am asking. Because to my locig x is every item in the array. So when I return x then it should return every item. But it returned them correctly without Booleans. Weird right?


#5

When you return x the item return (the value in the array) is evaluated like @ppc mentioned above.

You can test out what a value evaluates to with a simply if then else as follows. I will use the values in the array to demonstrate in the following code:

var arr = [7, "ate", "", false, 9];
for (var i = 0; i < arr.length; i++) {
  if (arr[i]) console.log(arr[i] + ' is true');
  else console.log(arr[i] + ' is false');
}

generates

7 is true
ate is true
 is false
false is false
9 is true

#6

As others have already stated, it because of coercion. Since the filter function is expecting a boolean value to be returned from the provided function, if it is not a boolean, then it automatically gets “coerced” into a boolean value. @rmdawson71 gave a good example of that. Then when something gets coerced into a false, the filter function leaves it out of the returned array.


#7

Thanks for this comprehensive reply, I fully understand now what’s going on there.

And thanks to everyone else replying.