TIL use JS filter like a pro
POSTED ON:
TAGS: javascript arrays
To remove falsy items, we use .filter()
(Array.prototype.filter())
, which returns a new array containing just the array items for which the function passed in to .filter()
evaluated to true.
You can use the Boolean constructor (Boolean()) to “coerce” a value to either true or false, which are the Boolean primitive types.
The question: #
Explain why you can abbreviate .filter(item=>Boolean(item))
to .filter(Boolean)
.
The first argument to .filter()
is a callback function, so you can pass in any existing function instead of making a new one.
In this case, Boolean
and (item)=>Boolean(item)
are the same callback function. (You can always try it in the console to be sure.)
Via this medium post - which is locked
(Kent C. Dodds’ .filter() Trick Will Change How You Use JavaScript)[https://medium.com/coding-at-dawn/kent-c-dodds-filter-trick-will-change-how-you-use-javascript-87b5112f9f6d]
Related TILs
Tagged: javascript