False values in JavaScript are false, null, 0, “”, undefined, and NaN. How do you tell if a value is one of them? For example, there is a requirement to remove all “false values” from an array.

function bouncer(arr) {
}

bouncer([7."ate"."".false.9]); // -> [7, "ate", 9]
Copy the code

How do you implement this approach to fulfill the requirements?

The answer is Boolean!!

MDN has an important note on this:

The value passed as the first argument is converted to a Boolean value if needed. If omitted or values 0, -0, null, false, NaN, undefined, or an empty string (“”), the object has an initial value of false. All other values, including any object, an empty array ([]) or the string “false”, create an object with an initial value of true.

Instead of converting a non-boolean to a Boolean by creating a Boolean object, use Boolean as a conversion function, or use double non-(!!). Operator:

var x = Boolean(expression);     / / recommend
varx = !! (expression);/ / recommend
var x = new Boolean(expression); / / not so good
Copy the code

So if you want to implement the bouncer(arr) method above, you can write:

function bouncer(arr) {
    return arr.filter(item= > {
        return Boolean(item); })}Copy the code

Or:

function bouncer(arr) {
    return arr.filter(item= > {
        return!!!!! item; })}Copy the code