To check if all values in array are false, use the array every()
method. The every()
method iterates over the array and compares each element to false
. If all array elements are false, then the every()
method will return true
; otherwise, it will return false
.
let arr1 = [false, false, false]; let arr2 = [true, false, false, true]; let result = arr1.every(element => element === false); console.log(result); //true result = arr2.every(element => element === false); 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 === false
). If any one of the array elements does not satisfy the condition, then the every()
method short-circuits and returns false
.
You can even use for...of loop to check if all values in array are false.
let arr1 = [false, false, false]; let arr2 = [true, false, false, true]; let result = true; for(let element of arr1){ if(element === true){ result = false; break; } } console.log(result); //true result = true; for(let element of arr2){ if(element !== false){ result = false; break; } } console.log(result); //false
If you are interested in checking if all values in the array are falsy, then you can use the same every()
method. In JavaScript, there are six falsy values: false
, 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); //false result = arr2.every(element => !element); console.log(result); //true