Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to remove falsy values from an array in JavaScript?
In JavaScript, falsy values are values that evaluate to false in a boolean context. These include false, 0, "", null, undefined, and NaN. Removing falsy values from an array is a common operation that can be accomplished using several methods.
What are Falsy Values?
JavaScript has six falsy values that evaluate to false when used in boolean contexts:
const falsyValues = [false, 0, "", null, undefined, NaN];
console.log("Falsy values:");
falsyValues.forEach(value => {
console.log(`${value} is falsy:`, !value);
});
Falsy values: false is falsy: true 0 is falsy: true is falsy: true null is falsy: true undefined is falsy: true NaN is falsy: true
Using Array.filter() (Recommended)
The most concise way to remove falsy values is using Array.filter() with the Boolean constructor:
const inputArray = [true, false, 0, "hello", "", null, 42, undefined, NaN, "world"];
console.log("Original array:", inputArray);
const filteredArray = inputArray.filter(Boolean);
console.log("After removing falsy values:", filteredArray);
Original array: [ true, false, 0, 'hello', '', null, 42, undefined, NaN, 'world' ] After removing falsy values: [ true, 'hello', 42, 'world' ]
Using forEach Loop
You can manually iterate through the array and push truthy values to a new array:
const inputArray = [true, false, 0, "hello", "", null, 42, undefined, NaN];
console.log("Original array:", inputArray);
function removeFalsy(arr) {
const result = [];
arr.forEach(item => {
if (item) {
result.push(item);
}
});
return result;
}
console.log("After removing falsy values:", removeFalsy(inputArray));
Original array: [ true, false, 0, 'hello', '', null, 42, undefined, NaN ] After removing falsy values: [ true, 'hello', 42 ]
Using filter() with Custom Logic
For more explicit control, you can use filter() with a custom callback:
const inputArray = [true, false, 0, "test", "", null, 123, undefined];
console.log("Original array:", inputArray);
const filtered = inputArray.filter(item => !!item);
console.log("After removing falsy values:", filtered);
Original array: [ true, false, 0, 'test', '', null, 123, undefined ] After removing falsy values: [ true, 'test', 123 ]
Comparison of Methods
| Method | Readability | Performance | Code Length |
|---|---|---|---|
filter(Boolean) |
Excellent | Fast | Very Short |
forEach loop |
Good | Fast | Longer |
filter(item => !!item) |
Good | Fast | Short |
Conclusion
The filter(Boolean) method is the most concise and readable approach for removing falsy values from arrays. It leverages JavaScript's built-in Boolean constructor to filter out all falsy values in a single, clean operation.
