How to Check if All Values are True in a JavaScript Array
If you ever need to check if an array only has true
values in JavaScript, you can use Array.every
in combination of the global Boolean
object:
const validations = [
true,
false,
'0',
undefined
null
];
const isEntirelyTrue = validations.every(Boolean);
// The above is equivalent to saying:
const isEntirelyTrue = validations.every(item => !!item);
const isEntirelyTrue = validations.every(item => item === true);
Explanation
The every
method tests whether all elements in the array pass the test that is implemented in the callback function. It is exactly what we need for this purpose. It always returns a boolean value: either true
or false
.
Combining this with the global Boolean
, which is a wrapper for boolean values, we can get the desired effect. It returns false
if the value is one of:
[0, -0, null, false, NaN, undefined, '']
Any other value will produce true
. It is equivalent of double negating a value to cast it to a boolean value, or comparing it to the boolean true
.
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: