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.
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.
filter(Boolean)` just removes values from a list which are "falsey", like empty strings or null.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With