Reputation: 147
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
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 offalse
. If the DOM objectdocument.all
is passed as a parameter, the new boolean object also has an initial value offalse
. All other values, including any object or the string"false"
, create an object with an initial value oftrue
.
function bouncer(arr) {
return arr.filter(Boolean);
}
Upvotes: 2
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