Borislav Hadzhiev
Sat Nov 13 2021·2 min read
Photo by Andreas Strandman
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.
// ✅ 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).
true
and 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
.
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.
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.