Check if all Values in an Object are False in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 12, 2021

banner

Photo from Unsplash

Check if all Values in an Object are False in JavaScript #

To check if all of the values in an object are equal to false, use the Object.values() method to get an array of the object's values and call the every() method on the array, comparing each value to false and returning the result.

index.js
// ✅ Check if false const obj1 = { isOpen: false, isActive: false, }; const areFalse = Object.values(obj1).every( value => value === false ); console.log(areFalse); // 👉️ true // ✅ Check if `falsy` const obj2 = { one: '', two: false, three: 0, }; const areFalsy = Object.values(obj2).every(value => !value); console.log(areFalsy); // 👉️ true

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

index.js
const obj1 = { isOpen: false, isActive: false, }; // 👇️ [false, false] 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 gets called with each element in the array of values, until it returns a falsy value or iterates over the entire array.

If the function returns a truthy value on all iterations, the every method returns true.

In the first example, we check if the value is equal to false on each iteration and return the result.

If the function returns a falsy value at least once, the every method short-circuits and returns false.

Checking if all values are equal to the boolean false is different compared to checking if all values are falsy.

The falsy values in JavaScript are: null, undefined, false, 0, "" (empty string), NaN (not a number). All other values in the language are truthy.

To check if an object only contains falsy values:

  1. Use Object.values() to get an array of the object's values.
  2. Call the every() method on the array.
  3. Convert each value to boolean, invert it, and return the result.
index.js
const obj2 = { one: '', two: false, three: 0, }; const areFalsy = Object.values(obj2).every(value => !value); console.log(areFalsy); // 👉️ true

All of the values in the object are falsy, so the test function passes on all iterations.

We used the logical NOT (!) operator to convert each value to a boolean and flip the result.

Here are some examples of using the logical NOT operator.

index.js
console.log(!true); // 👉️ false console.log(!false); // 👉️ true console.log(!'hello'); // 👉️ false console.log(!''); // 👉️ true console.log(!null); // 👉️ true

The operator converts each value to it's boolean representation and flips it.

If all of the values in the object are falsy, the test function we passed to the every method would return true on all iterations.

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.