Filter null from an array in JavaScript?

To filter null values from an array in JavaScript, use the filter() method. This method creates a new array containing only elements that pass a specified condition.

Syntax

array.filter(callback)

Method 1: Using Boolean Constructor

The simplest approach is to pass Boolean as the filter callback, which removes all falsy values including null, undefined, and empty strings.

var names = [null, "John", null, "David", "", "Mike", null, undefined, "Bob", "Adam", null, null];
console.log("Before filtering:");
console.log(names);

var filteredNames = names.filter(Boolean);
console.log("After filtering null/falsy values:");
console.log(filteredNames);
Before filtering:
[
  null, 'John',
  null, 'David',
  '', 'Mike',
  null, undefined,
  'Bob', 'Adam',
  null, null
]
After filtering null/falsy values:
[ 'John', 'David', 'Mike', 'Bob', 'Adam' ]

Method 2: Filtering Only null Values

If you want to keep other falsy values like empty strings but remove only null and undefined, use a specific condition:

var data = [null, "John", null, "David", "", "Mike", null, undefined, "Bob", 0, false, "Adam"];
console.log("Original array:");
console.log(data);

var filterOnlyNull = data.filter(item => item !== null && item !== undefined);
console.log("After filtering only null and undefined:");
console.log(filterOnlyNull);
Original array:
[
  null,     'John',
  null,     'David',
  '',       'Mike',
  null,     undefined,
  'Bob',    0,
  false,    'Adam'
]
After filtering only null and undefined:
[ 'John', 'David', '', 'Mike', 'Bob', 0, false, 'Adam' ]

Comparison of Methods

Method Removes null Removes undefined Removes empty strings Removes 0/false
filter(Boolean) Yes Yes Yes Yes
filter(item => item !== null) Yes No No No
filter(item => item != null) Yes Yes No No

Key Points

  • filter(Boolean) removes all falsy values (null, undefined, "", 0, false, NaN)
  • Use strict comparison (!== null) for precise filtering
  • The filter() method returns a new array without modifying the original
  • Loose equality (!= null) removes both null and undefined

Conclusion

Use filter(Boolean) for removing all falsy values, or filter(item => item !== null) for removing only null values. Both methods create clean arrays without null elements.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements