Check if all Object Properties are Null in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if all Object Properties are Null #

To check if an object's properties have a value of null:

  1. Use the Object.values() method to get an array of the object's values.
  2. Use the Array.every() method to iterate over the array.
  3. Check if each value is equal to null.
  4. The every() method will return true if all values are null.
index.js
const obj = {a: null, b: null}; const isNullish = Object.values(obj).every(value => { if (value === null) { return true; } return false; }); console.log(isNullish); // 👉️ true

We used the Object.values method to get an array of the object's values.

index.js
const obj = {a: null, b: null}; // 👇️ [null, null] console.log(Object.values(obj));

The function we passed to the Array.every method gets called with each value in the array.

If the value is equal to null, the function returns true, otherwise false is returned.

The Array.every method will return true only if the callback function returns true for all values in the array.

If the every() method returns true, then all of the object's values are null.

You can also check if the object's values are set to null, undefined or empty string, or any other value that your use case requires.

index.js
const obj = {a: null, b: undefined, c: ''}; const isNullUndefEmptyStr = Object.values(obj).every(value => { // 👇️ check for multiple conditions if (value === null || value === undefined || value === '') { return true; } return false; }); console.log(isNullUndefEmptyStr); // 👉️ true

The code sample checks if each value in the object is null, undefined or empty string.

We used the || (OR) operator, which means that only 1 of the 3 conditions has to be satisfied for the if block to run.

Check if all Object properties are Falsy #

You can also check if the values in an object are falsy. Falsy values in JavaScript are: false, 0, null, undefined, NaN and "" (empty string).

index.js
const obj = {a: null, b: undefined, c: '', d: 0, e: false}; const isFalsy = Object.values(obj).every(value => { if (!value) { return true; } return false; }); console.log(isFalsy); // 👉️ true

Our if statement checks if each value is falsy, by using the ! (not) operator.

If the callback function returns true on all invocations, then all of the object's values are falsy.

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.