How can I check whether every or any array item meets a condition?
Quick answer
Use array.every(predicate) to ask whether every visited item passes a condition; it returns true only when they all do. Use array.some(predicate) to ask whether at least one visited item passes; it returns true when it finds a match. For example, with [1, 2, 3] and an even-number predicate, every() is false while some() is true. [S1] [S2]
The question, the details, the next step.
A practical checklist
Write the condition as a predicate that returns a truthy or falsy result for one item.
Use
every(predicate)when the requirement is that all visited items pass.Use
some(predicate)when one or more matching items are enough.Test your intended case and read the boolean result against the question you asked.
Decide explicitly what an empty array should mean in your application.
A few more useful answers
Can `every()` and `some()` both return true for the same array?
Does `some()` mean exactly one item matches?
No. It means at least one item matches; it can be one item or several. Use a different counting approach if you need to know how many match.
Sources
References used for this guide.
- [S1] Array.prototype.every() - JavaScript | MDN developer.mozilla.org · Checked
- [S2] Array.prototype.some() - JavaScript | MDN developer.mozilla.org · Checked
