Check if all Values in an Object are False in JavaScript

avatar

Borislav Hadzhiev

Fri Nov 12 20212 min read

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 #

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