user4841711
user4841711

Reputation:

How does passing Boolean as an argument work?

Okay, the problem was, given an array, remove all elements that are 'falsey'.

This was my solution to said 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]);

This works, and passes the tests. But here's the solution that was given:

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

I've read the MDN article on Boolean AND filter and still don't get how this works? What exactly is happening here? Is Boolean the callback function? If so, how does that work, in the back end? I'm just sitting here scratching my head.

Upvotes: 3

Views: 270

Answers (4)

Jows
Jows

Reputation: 461

arr.filter(Boolean);

is the same than

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

Since Boolean constructor is also a function, it returns either true for ‘truthy’ argument or false for ‘falsy’ argument.

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

Upvotes: 0

Weedoze
Weedoze

Reputation: 13953

The Boolean object is an object wrapper for a boolean value. When calling Boolean you are actually calling a function (See snippet) with a parameter - Exactly what you need in the callback for Array.filter().

new Boolean([value]) is called

Depending on the parameter, the returned value will be true or false (See snippet).

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

Upvotes: 1

Nisarg Shah
Nisarg Shah

Reputation: 14562

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

The code above is equivalent to:

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

Also, Boolean returns false when passed a falsey parameter. As a result those are filtered out.

Upvotes: 0

Quentin
Quentin

Reputation: 944568

From filter:

callback Function is a predicate, to test each element of the array. Return true to keep the element, false otherwise

From Boolean

The value passed as the first parameter is converted to a boolean value

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

Upvotes: 3

Related Questions