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
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:
With that in mind, on with the post! 😄
The first thing you’d want to do is get the checkboxes using the
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:
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:
- The current item being processed in the array;
- The index of the current item; and
- The array this method was called upon.
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:
To see if every item in my
checkboxes array is checked, all I have to do is pass my
isChecked() function into the
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!