Borislav Hadzhiev
Fri Nov 12 2021·2 min read
Photo by Meiying Ng
To check if all of the values in an object are equal to true
, use the
Object.values()
method to get an array of the object's values and call the
every()
method on the array. The every
method will test whether all values
in the array have a value of true
and return the result.
// ✅ Check if equal to `true` const obj1 = { first: true, second: true, }; const areTrue = Object.values(obj1).every( value => value === true ); console.log(areTrue); // 👉️ true // ✅ Check if `truthy` const obj2 = { first: 'hello', second: true, third: 1, }; const areTruthy = Object.values(obj2).every( value => value ); console.log(areTruthy); // 👉️ true
We used the Object.values method to get an array of the object's values.
const obj1 = { first: true, second: true, }; // 👇️ [true, true] console.log(Object.values(obj1));
The next step is to use the Array.every method on the result.
The function we passed to the every
method is a test function that gets tested
for each element in the array.
every
method short-circuits and returns false
.If the condition is met for all elements in the array, the every
method
returns true
.
In our first example, we explicitly check if the value is equal to true
.
There is a distinction between the boolean value true
and a truthy
value.
The falsy values in JavaScript are: null
, undefined
, false
, 0
, ""
(empty string), NaN
(not a number). All other values in the language are
truthy.
If you return any other (than the aforementioned 6 values) for all iterations of
the every
method, the method ends up returning true
.
To check if an object only contains truthy values:
Object.values()
to get an array of the object's values.every()
method on the array.const obj2 = { first: 'hello', second: true, third: 1, }; const areTruthy = Object.values(obj2).every(value => value); console.log(areTruthy); // 👉️ true
All of the values in the object are truthy, so the test function passes on all iterations because we return each value as is.
An alternative approach is to use a shorthand method, where we leverage the
Boolean
object.
To check if an object only contains truthy values:
Object.values()
method to get an array of the object's values.Boolean
object to the every()
method.every
method will return true
if all object values are truthy.// ✅ Check if `truthy` const obj2 = { first: 'hello', second: true, third: 1, }; const areTruthyShort = Object.values(obj2).every(Boolean); console.log(areTruthyShort); // 👉️ true
The Boolean
object converts each element from the array of values to its
boolean representation and returns the result.
This code snippet achieves the same result as the previous one, however is a little more concise and implicit.
every
method as I find it easier to read and more direct.