Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
boolean
communitycreator

How to quickly filter out all falsy values from an array in JS

Non Stop Learning...

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

function(currentValue, index, array)

Required. A function or search criteria to be used to filter values in the array.

The function accepts three arguments:



CurrentValue (Required) - The current element that needs to be filtered.

Index (Optional) - The index of the current element being processed in the array.

Array (Optional) - The array object being called upon.



thisValue

thisValue is passed in case the parameter is empty.

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 , "", and false.

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.

RELATED TAGS

javascript
boolean
communitycreator

CONTRIBUTOR

Non Stop Learning...
RELATED COURSES

View all Courses

Keep Exploring