How to get only falsy values instead?

Tell us what’s happening:

solving the challenge was quite easy! but when I checked the other solutions
I found this one

Your code so far


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

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

I expect this code should return boolean values only, but it returns !falsy values,
okay but what if I wanted to get the falsy values instead?
I tried this bellow but it didn’t work

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36.

Challenge: Falsy Bouncer

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer

Hint: if someFalseyValue is anything that is falsy, then !someFalseyValue is true.

Another hint: JavaScript is dynamically typed, and does type coercion on every element if you don’t use a more strict comparison.

1 Like

Boolean is a function. The filter method will return a new array with only the elements where the function supplied returns a value of true. When any falsy value is called as an argument to the Boolean function, it will return false and hence not be included.

In your second bouncer function, putting the ! in front of Boolean coerces Boolean (which is a function and all functions are truthy) into the value false. The value false is not a function, so you get a TypeError as the filter attempts to call it.

2 Likes

now I understand how Boolean is can be input to filter()
but back to my first question, how to get the falsy values only on that array

That’s what @Rybar and I were giving you hints about.

could you be more verbose or rephrase that
I couldn’t understand you or @Rybar

You will need to write a filter function rather than using Boolean.

1 Like

Boolean is a function, like that filter is using that function as callback
same as you would write

function isItEven (num) {
 return num % 2 === 0;
}
arr.filter(isItEven);

you need to create the callback yourself
you can’t just do

arr.filter(!isItEven)

if you still have difficulties I can show an example on how to flip the thing using this case

1 Like