Check if all Values in Array are False in JavaScript

avatar

Borislav Hadzhiev

Sat Nov 13 20212 min read

banner

Photo by Raychan

Check if all Values in Array are False #

To check if all of the values in an array are equal to false, use the every() method to iterate over the array and compare each value to false, e.g. arr.every(value => value === false). The every method will return true if all array elements are equal to false.

index.js
// โœ… All are equal to `false` function allAreFalse(arr) { return arr.every(element => element === false); } console.log(allAreFalse([false, false])); // ๐Ÿ‘‰๏ธ true console.log(allAreFalse([false, true])); // ๐Ÿ‘‰๏ธ false // โœ… All are falsy function allAreFalsy(arr) { return arr.every(element => !element); } console.log(allAreFalsy([0, '', false])); // ๐Ÿ‘‰๏ธ true console.log(allAreFalsy([1, 'test', true])); // ๐Ÿ‘‰๏ธ false

The function we passed to the Array.every method gets called with each element in the array until it returns a falsy value or iterates over the entire array.

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

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

In the first example, we check if each element in the array is equal to falseand return the result. If the condition is met for all array elements, theevery method returns true.

Note that checking if a value is equal to false is different than checking if the value is falsy.

To check if all values in an array are falsy, use the every() method to iterate over the array, convert each value to boolean, negate it, and return the result. If all values in the array are falsy, the every method will return true.

index.js
function allAreFalsy(arr) { return arr.every(element => !element); } console.log(allAreFalsy([0, '', false])); // true console.log(allAreFalsy([1, 'test', true])); // false

On each iteration, we used the logical NOT (!) operator to convert each value to boolean and invert the result.

Here are some examples of using the logical NOT (!) operator.

index.js
console.log(!true); // ๐Ÿ‘‰๏ธ false console.log(!false); // ๐Ÿ‘‰๏ธ true console.log(!'str'); // ๐Ÿ‘‰๏ธ false console.log(!''); // ๐Ÿ‘‰๏ธ true console.log(!null); // ๐Ÿ‘‰๏ธ true

If the array contains only falsy values, the function we passed to the every() method would return true on all iterations and pass the test.

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