All Must Match
every returns true only if all elements pass the test.
It stops early when it finds a failing element.
JavaScript Tutorial
every checks whether all elements in an array satisfy a condition.
It returns true only if every item passes.
Many validation tasks require confirming all items are valid.
every expresses this clearly and stops early for efficiency.
array.every((value, index, array) => condition)const nums = [2, 4, 6];
const allEven = nums.every((n) => n % 2 === 0);
console.log(allEven);All items match, so result is true.
const nums = [2, 3, 4];
const allEven = nums.every((n) => n % 2 === 0);
console.log(allEven);One item fails, so result is false.
every returns true only if all elements pass the test.
It stops early when it finds a failing element.
every is great for validation rules like all fields filled.
If you need any match, use some instead.
every on an empty array returns true by definition.
Handle this case if it matters.
const fields = ["name", "email"];
const valid = fields.every((f) => f.length > 0);
console.log(valid);Use every to validate all fields.
const users = [{ active: true }, { active: true }];
const allActive = users.every((u) => u.active);
console.log(allActive);Works with arrays of objects too.
Without
let allValid = true;
for (const n of nums) {
if (n <= 0) {
allValid = false;
break;
}
}With
const allValid = nums.every((n) => n > 0);Use some when you need at least one match.
Check array length when needed.
every returns a boolean, not items.
True.
When all elements must satisfy a condition.
every requires all; some requires any.
Practice: Check if all scores are 50 or above.
const scores = [70, 55, 40];
// TODO: check all >= 50
One Possible Solution
const scores = [70, 55, 40];
const ok = scores.every((s) => s >= 50);
console.log(ok);A boolean indicating if all items pass the test.
Yes, it stops when a failure is found.
every returns true for empty arrays.
Try arrays with mixed values to see results.