How to Remove Falsy Values From an Array in Javascript

Wednesday, April 21, 2021 • One minute to read

Javascript2021to-the-pointjavascript2021to-the-point

Falsy Values in the Javascript

In Javascript, in the context of Boolean all the values are either true or false.

For Example

Boolean Values
True 1,2,3, “any string”, {} , true, 1.0, ‘false’, Infinity
False 0, -0, false, 0n, “", ‘',``, null, undefined, NaN |

‘false’ is a string.

Demo

Use filter to remove all the falsy values from an array.

1const arr = ["hi", '', false, 123, {}, [], "false", 0];
2// falsy values are '' false 0
3const newArr = arr.filter(Boolean); // ["hi", 123, {}, [], "false"]

filter returns a new array instead of updating the original array.


Javascript2021to-the-pointjavascript2021to-the-point

PreviousHow to Convert Nested Arrays Into 1d Array in Javascript

NextHow to Get the Length of an Object in Javascript