To check if all values in array are true, use the array every()
method. The every()
method loops through the array and compares each array element to true
. If all array elements satisfy the condition, then the every()
method will return true
; otherwise, it will return false
.
let arr1 = [true, true, true]; let arr2 = [true, false, false, true]; let result = arr1.every(element => element === true); console.log(result); //true result = arr2.every(element => element === true); console.log(result); //false
The explanation of the code is as follows:
The every()
method calls a callback function for each element of the array. Inside the callback function, you specify the condition (element === true
). If any one of the elements does not satisfy the condition, then the every()
method short-circuits and returns false
.
You can also use for...of loop to check if all values in array are true.
let arr1 = [true, true, true]; let arr2 = [true, false, false, true]; let result = true; for(let element of arr1){ if(element === false){ result = false; break; } } console.log(result); //true result = true; for(let element of arr2){ if(element !== true){ result = false; break; } } console.log(result); //false
If you are interested in checking if all values in the array are truthy, then you can use the same every() method. The every() method returns true
when all array elements are truthy. On the other hand, if any one of the elements is falsy, then the every() method returns false
.
It is essential to understand what truthy and falsy values in JavaScript are? Actually, in JavaScript alongside false
, the following are considered falsy values: null
, undefined
, NaN
, ""
(empty string), and 0
. All other values except falsy are truthy.
let arr1 = [27, "JavaScript", true]; let arr2 = [0, undefined, ""]; let result = arr1.every(element => element); console.log(result); //true result = arr2.every(element => element); console.log(result); //false