Skip to content
Advertisement

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.

Advertisement

Answer

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;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement