πŸŽ„ Get 20% off from our JavaScript course for the holidays! πŸŽ„
How to Check if All Values are True in a JavaScript Array

How to Check if All Values are True in a JavaScript Array

Ferenc Almasi β€’ 2021 May 04 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

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:

Copied to clipboard! Playground
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:

Copied to clipboard!
[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.

How to Check if All Values are True in a JavaScript Array
If you would like to see more Webtips, follow @flowforfrank

Why Do You Need to Know About Functional Programming?

Resources:

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access exclusive interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Remove ads to learn without distractions
Become a Pro

Recommended