jimpix
jimpix

Reputation: 147

How does this function remove all falsy values from an array?

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

This function removes all falsy values from an array. I don't understand how it works. Does filter automatically only return non-falsy values?

Upvotes: 1

Views: 687

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386746

You could use Boolean as well for filtering truthy values.

It returns a boolean value for every value.

The value passed as the first parameter is converted to a boolean value, if necessary. If the value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. If the DOM object document.all is passed as a parameter, the new boolean object also has an initial value of false. All other values, including any object or the string "false", create an object with an initial value of true.

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

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1075219

Because filter calls the callback with each value from the array, and builds a new array that includes only the values for which filter returned a truthy value. So returning the value from the callback only retains truthy values (non-falsy ones), because when the callback returns a falsy value, filter leaves that entry out of the array it builds.

For details on how filter works, see MDN (readable) or the specification (markedly less so, but definitive).

Upvotes: 4

Related Questions