Check if all Values in Array are True in JavaScript

avatar

Borislav Hadzhiev

Sat Nov 13 20212 min read

Check if all Values in Array are True #

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

index.js
// โœ… All are equal to `true` function allAreTrue(arr) { return arr.every(element => element === true); } console.log(allAreTrue([true, true])); // ๐Ÿ‘‰๏ธ true console.log(allAreTrue([true, false])); // ๐Ÿ‘‰๏ธ false // โœ… All are truthy function allAreTruthy(arr) { return arr.every(element => element); } console.log(allAreTruthy([1, 'test', true])); // ๐Ÿ‘‰๏ธ true console.log(allAreTruthy([0, '', 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).

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

There is a distinction between a value being equal to true and a value being truthy.

Truthy values in JavaScript are all values that are not falsy. In other words, all values other than the aforementioned 6 falsy values.

To check if all values in an array are truthy, use the every() method to iterate over the array and return each value straight away. If all values in the array are truthy, the every method will return true, otherwise it returns false.

index.js
function allAreTruthy(arr) { return arr.every(element => element); } console.log(allAreTruthy([1, 'test', true])); // ๐Ÿ‘‰๏ธ true console.log(allAreTruthy([0, '', true])); // ๐Ÿ‘‰๏ธ false

The every method checks if the passed in callback function returns a truthy value, so we can directly return the value from the array.

An alternative and a little more concise approach is to use the Boolean object.

index.js
function allAreTruthy(arr) { return arr.every(Boolean); } console.log(allAreTruthy([1, 'test', true])); // ๐Ÿ‘‰๏ธ true console.log(allAreTruthy([0, '', true])); // ๐Ÿ‘‰๏ธ false

The Boolean object gets passed each value in the array, converts the value to its boolean representation and returns the result.

This achieves the same goal as our previous example, where we returned the array element directly.

This approach is a bit more implicit and harder to read, so I prefer explicitly returning each element from the array.

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