How does handling Boolean as an argument work?

Ok, the problem is that an array is given, remove all elements that are "false".

This was my solution to the above problem (which works):

function bouncer(arr) {
  var trueArr = [];
  for(i=0; i<arr.length; i++){
        if (arr[i]){
            trueArr.push(arr[i]);
        }
    }
  return(trueArr);
}

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

      

It works and passes tests. But here is the solution that was given:

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

      

I've read the MDN article about Boolean AND filter and still don't understand how it works? What exactly is going on here? Boolean callback functions? If so, how does it work, in the end? I just sit there, scratching my head.

+3


source to share


4 answers


Boolean

object is an object wrapper for a boolean value. When called, Boolean

you are actually calling the function (see snippet) with a parameter - exactly what you need in the callback for Array.filter()

.

new Boolean([value])

called

Depending on the parameter, the return value will be true

or false

(see snippet).



console.log(Boolean); //Constructor
console.log(Boolean(0)); //Falsy value
console.log(Boolean("foo")); //Truthy value
      

Run codeHide result


+1


source


From filter :

Callback The function is a predicate for checking each element of the array. True to save the item, otherwise false

From Boolean



The value passed as the first parameter is converted to boolean

So yes. This is a callback. It is a function (built into the JS language) that returns true or false what the filter function expects from the function passed to it.

+2


source


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

      

The above code is equivalent:

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

      

It also Boolean

returns false

false when the parameter is passed. As a result, they are filtered out.

0


source


arr.filter(Boolean);

      

coincides with

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

      

Since the boolean constructor is also a function, it returns either true for a "true argument" or "false" for a false argument.

http://www.devign.me/javascript-tip-remove-falsy-items-out-of-an-array

0


source







All Articles