dSumner.1289
dSumner.1289

Reputation: 712

Using "Boolean" as the argument to .filter() in JavaScript

Recently I've learned that you can use the Boolean keyword to check whether a boolean value is false, e.g. this, where the arrayOfSheeps is simply an array of boolean values.

function countSheeps(arrayOfSheeps) {
  return arrayOfSheeps.filter(Boolean).length;
}

As I've been unable to find anything about using 'Boolean' as a keyword, I was wondering if there are any other uses for the word, or even just any resources I can use to learn about it.

Upvotes: 34

Views: 15134

Answers (2)

Derek Liang
Derek Liang

Reputation: 1222

Based on MDN Boolean,

Do not use a Boolean object to convert a non-boolean value to a boolean value. To perform this task, instead, use Boolean as a function

var x = Boolean(expression);     // use this...
var x = !!(expression);          // ...or this
var x = new Boolean(expression); // don't use this!

So the code is same as:

const b = v => !!v;
arrayOfSheeps.filter(b).length;
arrayOfSheeps.filter(v => !!v).length;  // or inline 

Upvotes: 0

elclanrs
elclanrs

Reputation: 94131

Boolean is not a keyword, it is a function, and functions are just objects, that you can pass around. It is the same as:

return arrayOfSheeps.filter(function(x){return Boolean(x)}).length;

Since function(x){return f(x)} === f then you can simplify:

return arrayOfSheeps.filter(Boolean).length;

Upvotes: 42

Related Questions