List of falsy value
In JavaScript, the following values are considered falsy:
-
false
: The boolean valuefalse
. -
0
: The number zero (numeric zero). -
''
or""
: An empty string. -
null
: The absence of any value. -
undefined
: A variable that has been declared but has not been assigned a value. -
NaN
: Not-a-Number, which represents an invalid or unrepresentable value in numeric operations.
These values are considered falsy because they evaluate to false
when used in a boolean context. Any other value that is not explicitly falsy is considered truthy.
How to remove falsy value from array
To remove falsy values from an array in JavaScript, you can use various approaches. Here are a few methods you can use:
- Using
Array.prototype.filter()
:
const arr = [0, false, null, undefined, '', 1, 2, 'hello'];
const filteredArr = arr.filter(Boolean);
console.log(filteredArr); // Output: [1, 2, 'hello']
In this approach, the filter()
method is called on the array and passed a callback function. The callback function uses the Boolean
constructor as the predicate, which filters out any falsy values from the array.
- Using a
for...of
loop:
const arr = [0, false, null, undefined, '', 1, 2, 'hello'];
const filteredArr = [];
for (const value of arr) {
if (value) {
filteredArr.push(value);
}
}
console.log(filteredArr); // Output: [1, 2, 'hello']
In this approach, a for...of
loop is used to iterate over the array. Each value is checked using an if
statement, and only truthy values are added to the filteredArr
using the push()
method.
- Using
Array.prototype.reduce()
:
const arr = [0, false, null, undefined, '', 1, 2, 'hello'];
const filteredArr = arr.reduce((result, value) => {
if (value) {
result.push(value);
}
return result;
}, []);
console.log(filteredArr); // Output: [1, 2, 'hello']
In this approach, the reduce()
method is used to iterate over the array. The callback function checks each value and adds truthy values to the result
array.
- Using custom filtering function :
const arr = [0, false, null, undefined, '', 1, 2, 'hello'];
const filteredArr = arr.filter(function (element) {
return !!element; // Double negation to convert value to boolean
});
console.log(filteredArr); // Output: [1, 2, 'hello']
All of these approaches will remove falsy values from the array and return a new array containing only truthy values.
Top comments (2)
Not tested it in a while, but last time I did:
performed considerably better than using
Boolean
.Thank you for your input and for sharing your experience regarding the performance of arr.filter(x => x) versus using Boolean. It's always valuable to hear different perspectives and insights.
I found arr.filter(x=>x) performs consistently better compared to arr.filter(Boolean).
Once again, thank you for sharing your experience and raising this point.