Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 447
dSumner.1289 Avatar asked Mar 31 '15 00:03

dSumner.1289


People also ask

What does filter Boolean do in JavaScript?

The filter(Boolean) step does the following: Passes each item in the array to the Boolean() object. The Boolean() object coerces each item to true or false depending on whether it's truthy or falsy. If the item is truthy, we keep it.

What does filter Boolean mean?

filter(Boolean)` just removes values from a list which are "falsey", like empty strings or null.

What is filter Boolean I typescript?

filter(Boolean as any as ExcludesFalse); This works because you are asserting that Boolean is a type guard, and because Array. filter() is overloaded to return a narrowed array if the callback is a type guard.

Can we use Boolean in JavaScript?

In JavaScript, a boolean value is one that can either be TRUE or FALSE. If you need to know “yes” or “no” about something, then you would want to use the boolean function. It sounds extremely simple, but booleans are used all the time in JavaScript programming, and they are extremely useful.


1 Answers

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; 
like image 193
elclanrs Avatar answered Sep 25 '22 23:09

elclanrs