Borislav Hadzhiev
Wed Oct 06 2021·2 min read
Photo by Toa Heftiba
To check if an object's properties have a value of null
:
Object.values(obj)
method passing in the object. The
Object.values
method returns an array of the object's values.Array.every
method passing it a function.null
and return true
in that casenull
, then the object's properties contain only
null
valuesconst 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
.
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.
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
.
You can also check if the values of an object are falsy
.
Falsy values in
JavaScript are: false
, 0
, null
, undefined
, NaN
.
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
.