Codectionary / Developer documentation / JavaScript

some() and every()

some() tests whether at least one array element passes a condition, returning true as soon as it finds a match (or false if none do). every() tests whether all elements pass a condition, returning false as soon as it finds one that fails (or true if all pass). Both short-circuit for efficiency.

Syntax

arr.some(item => condition)
arr.every(item => condition)

Examples

some() - At Least One Match

Checking whether any element satisfies a condition.

const numbers = [1, 3, 5, 8, 9];

console.log(numbers.some(n => n % 2 === 0)); // true - 8 is even
console.log(numbers.some(n => n > 100));      // false - none are

every() - All Must Match

Checking whether every element satisfies a condition.

const ages = [22, 25, 30, 18];

console.log(ages.every(age => age >= 18)); // true - all are adults
console.log(ages.every(age => age >= 21)); // false - 18 fails the check

Practical Validation Example

A common real-world use: form validation.

const formFields = [
  { name: "email", value: "user@test.com" },
  { name: "password", value: "" },
  { name: "username", value: "bob" }
];

const allFilled = formFields.every(field => field.value.length > 0);
console.log(allFilled); // false - password is empty

const hasEmptyField = formFields.some(field => field.value.length === 0);
console.log(hasEmptyField); // true

Best practices

  • Use some() instead of filter().length > 0 when you only need a true/false answer - it stops early, which is more efficient
  • Use every() for validation checks where all items must satisfy a rule, like confirming every required field is filled
  • Remember every() on an empty array always returns true (vacuous truth), and some() on an empty array always returns false
  • Combine some()/every() with logical operators for readable, declarative validation logic

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation