Check if all Object Properties are Null in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 06 20212 min read

banner

Photo by Toa Heftiba

Check if all Object Properties are Null #

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

  1. Call the Object.values(obj) method passing in the object. The Object.values method returns an array of the object's values.
  2. Call the Array.every method passing it a function.
  3. The function should check if each value is equal to null and return true in that case
  4. If all values are equal to null, then the object's properties contain only null values
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

The function we pass to the Array.every method, will get called with each value.

If the value is equal to null we return true, otherwise we return false.

The Array.every method will return true only if our callback function returns true on all invocations.

In that case we know that all of the object's values are null.

You can also check if the values are set to null, undefined or empty string, or pretty much whatever 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 snippet checks if each value in the object is null, undefined or empty string.

Notice that we use the || (or) operator, which means that only 1 of the 3 conditions has to be satisfied for the if block to run and return true.

Check if all Object properties are Falsy #

You can also check if the values of an object are falsy. Falsy values in JavaScript are: false, 0, null, undefined, NaN.

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

In the if statement we check if the value is falsy, by using the ! (not) operator. If the value is falsy, return true.

If all invocations of the function we passed to the Array.every method return true, then all of the object's values are falsy.

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