Get rid of falsy values from Array

Falsy Values In Javascript

Harsha
TheLeanProgrammer
Feb 3, 2022

--

Thinking what are falsy values?

Well, A falsy value is a value that is considered false when encountered in a Boolean context.

In javascript falsy values are

1. null

2. undefined

3. NaN

4. 0

5. -0

6. 0n (BigInt zero)

7. false

8. “” (empty string)

Easiest way to remove these falsy values from Array is to use filter method with Boolean function.

Suppose Array is

myArray =[1, true, NaN, null, ‘hello’, 0, 78, {}, undefined,’’,false, ‘truthy’];

let newArray = myArray.filter(Boolean)

newArray will be [1, true, ’hello’, 78, {}, ‘truthy’];

Isn’t that easy?

Happy learning!!!

Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter tinyletter.com/TheLeanProgrammer

--

--