Array Every Method
every() returns true if the callback returns a truthy value for every element of an array, and false if it fails for any one of them. It is the counterpart of some(), which asks whether at least one element passes.
const marks = [62, 48, 71, 55];
console.log(marks.every((mark) => mark >= 40));console.log(marks.every((mark) => mark >= 50));This prints:
truefalseIt stops at the first failure
Section titled “It stops at the first failure”every() stops as soon as one element fails, because one failure settles the answer. Here the check never reaches the phone number:
const fields = [ { name: 'email', value: 'asha@example.com' }, { name: 'postcode', value: '' }, { name: 'phone', value: '01632 960123' },];
const complete = fields.every((field) => { console.log(`checking ${field.name}`); return field.value !== '';});
console.log(complete);This prints:
checking emailchecking postcodefalseIf you need to know every field that failed, not just whether one did, use filter() instead.
An empty array passes
Section titled “An empty array passes”On an empty array every() returns true, because there is no element that fails. This is the logical rule known as vacuous truth, and it can catch you out. A check that “every selected item is in stock” passes when nothing is selected at all, so add a length check where an empty list should fail.
const selectedItems = [];
console.log(selectedItems.every((item) => item.inStock));console.log(selectedItems.length > 0 && selectedItems.every((item) => item.inStock));This prints:
truefalseSteve Griffith covers this topic in his video JavaScript Array every method.