How to check if every item in an array meets a condition

In vanilla JS, you might want to run some code only if every item in an array meets a condition. Let’s look at how you can do just that using the native Array.every() method!

This is not an April Fools’ Day post, because fuck tradition 🙃

For our example, let’s say you want to run some code only if all the checkboxes on a page are checked.

My good friend Chris Ferdinandi has reminded me that you could just get all the checked items using the :checked CSS selector:

// Get all the checked checkboxes
var checked = document.querySelectorAll("[type='checkbox']:checked");

With that in mind, on with the post! 😄

The first thing you’d want to do is get the checkboxes using the Document.querySelectorAll() method.

This returns a NodeList, though, which is similar to an array but doesn’t have access to the Array.every() method. So you’d first need to convert the NodeList to an array:

// Get all the checkboxes as a NodeList
var checkboxes = document.querySelectorAll("[type='checkbox']");

// Convert the NodeList to an array
checkboxes = Array.prototype.slice.call(checkboxes);

The Array.every() method expects a callback function. It returns true if said callback function returns a truthy value for every item in the array; otherwise, it returns false. The possible parameters for the callback function are:

Only the first argument is required.

You could use an anonymous function, but I prefer to avoid anonymous functions wherever possible. I’ll use a named function instead. Specifically, I’ll use the isChecked() function I created for yesterday’s post:

/**
 * Check if a checkbox is checked
 * @param   {Node} checkbox The checkbox
 * @returns {Boolean}       Whether the checkbox is checked or not
 */
var isChecked = function (checkbox) {
  return checkbox.checked;
};

To see if every item in my checkboxes array is checked, all I have to do is pass my isChecked() function into the Array.every() method:

// Do something if all checkboxes are checked
if (checkboxes.every(isChecked)) {...}

This method is supported in IE9 and above, but if you need it to work in older browsers, you can extend support further using a polyfill.


If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!