Check if all Values in Array are Null in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if all Values in Array are Null #

To check if all of the values in an array are equal to null, use the every() method to iterate over the array and compare each value to null, e.g. arr.every(value => value === null). The every method will return true if all values in the array are equal to null.

index.js
function allAreNull(arr) { return arr.every(element => element === null); } console.log(allAreNull([null, null])); // 👉️ true console.log(allAreNull([null, undefined])); // 👉️ false

We created a reusable function that checks if all the values in an array are equal to null.

The function we passed to the Array.every method gets called with each element in the array until it returns a falsy value or iterates over the entire array.

If the function returns a falsy value at least once, the every method short-circuits also returning false.

The falsy values in JavaScript are: false, null, undefined, 0, "" (empty string), NaN (not a number).

On each iteration, we check if the current value in the array is equal to null using the strict equality (===) operator.

If the condition is met for all array elements, the every method will return true.

If the condition fails at least once, the every method will short-circuit and will return false. This is useful because we don't want to keep iterating, once we've found the answer.

An alternative approach is to use the for...of loop.

To check if all of the values in an array are equal to null:

  1. Use the for...of loop to iterate over the array.
  2. On each iteration, compare the current value to null.
  3. If the value is not equal to null, break out of the loop and return false.
index.js
function allAreNull(arr) { let result = true; for (const value of arr) { if (value !== null) { result = false; break; } } return result; } console.log(allAreNull([null, null])); // 👉️ true console.log(allAreNull([undefined, null])); // 👉️ false

The code sample achieves the same result by using a more manual approach.

We declared a result variable and set it to true.

If any of the values in the array is not equal to null, we reassign the result variable to false, break out of the loop and return false from the function.

The break keyword is used to exit the current loop.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.