Skip to content

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.

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

Where the arrayOfSheeps is simply an array of boolean values. 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.

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;