Check if all Values in Array are Null in JavaScript

avatar

Borislav Hadzhiev

Sat Nov 13 20212 min read

banner

Photo by Raychan

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 of 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 return false. This is useful, because we don't want to keep iterating, even though 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, use the for...of loop to iterate over the array and compare each value to null. 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

This is a more manual approach to achieve the same result as in the previous example.

We declare 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 allows us to exit a loop, once the work is done.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee