How to quickly filter out all falsy values from an array in JS
We use the filter method to remove falsy values from an array. The filter method filters out all the values that return false when passed to a function. When you use filter and pass a Boolean constructor, you can quickly filter out all the falsy values from the array.
Syntax
array.filter(function(currentValue, index, array), thisValue)
Parameters
Parameter | Description |
(Required) | A function or search criteria to be used to filter values in the array. The function accepts three arguments:
|
(Optional) |
|
Return value
filter returns a new array with the elements that pass the test. If no elements pass the test, an empty array will be returned.
Note: There are only six falsy values in JavaScript:
undefined,null,NaN,0,"", andfalse.
Code
const arr = [1, "test", undefined, null, 5, false, "", 3, NaN];const result = arr.filter(Boolean); // = > [1, "test", 5, 3]console.log(result);
Explanation
- Javascript has first-class functions. This is why you can directly pass the Boolean constructor function to
filter. arr.filter(Boolean)filters all the falsy values present in the array and returns a new array.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved