Episode 1 — Fundamentals / 1.22 — Array Methods

1.22.e — some() and every()

In one sentence: some() returns true if any element passes the test (short-circuits on first match), while every() returns true only if all elements pass (short-circuits on first failure).

Navigation: ← 1.22.d — forEach() · 1.22.f — slice() and splice() →


1. some() — does ANY element pass?

some() iterates through the array and returns true as soon as one element's callback returns truthy. If none pass, it returns false.

const ages = [14, 17, 21, 16];
const hasAdult = ages.some(age => age >= 18);

console.log(hasAdult); // true — 21 passes, stops checking after that

Syntax

const result = arr.some(callback(element, index, array));
// Returns: true or false

Short-circuiting

some stops as soon as it finds a truthy result. It does not visit remaining elements.

const nums = [1, 2, 3, 4, 5];
nums.some(n => {
  console.log(`Checking ${n}`);
  return n === 3;
});
// Checking 1
// Checking 2
// Checking 3    ← stops here, returns true
// (4 and 5 never checked)

2. every() — do ALL elements pass?

every() iterates through the array and returns true only if every element's callback returns truthy. Returns false as soon as one fails.

const scores = [85, 92, 78, 96];
const allPassing = scores.every(s => s >= 60);

console.log(allPassing); // true — all >= 60

Syntax

const result = arr.every(callback(element, index, array));
// Returns: true or false

Short-circuiting

every stops as soon as it finds a falsy result:

const nums = [2, 4, 5, 6, 8];
nums.every(n => {
  console.log(`Checking ${n}`);
  return n % 2 === 0;
});
// Checking 2
// Checking 4
// Checking 5    ← 5 is odd, stops here, returns false
// (6 and 8 never checked)

3. Empty array behavior (vacuous truth)

This is a classic interview question:

[].some(x => x > 0);   // false — no element can be true
[].every(x => x > 0);  // true  — no element can be false (vacuous truth)
MethodEmpty array returnsLogic
some([])false"Is there at least one?" — No, there are zero.
every([])true"Do all pass?" — Yes, vacuously (no counterexample exists).

Vacuous truth is a concept from formal logic: a universal statement about an empty set is always true because there are no counterexamples.


4. Side-by-side comparison

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

numbers.some(n => n % 2 === 0);   // true  — 8 is even
numbers.every(n => n % 2 === 0);  // false — 1 is not even
numbers.every(n => n > 0);        // true  — all positive
numbers.some(n => n > 100);       // false — none > 100
Checksomeevery
At least one even?true (8)N/A
All even?N/Afalse (1)
All positive?N/Atrue
Any > 100?falseN/A

5. Replaces manual loop-and-flag patterns

Before (manual flag)

// Check if any student failed
let hasFailing = false;
for (const student of students) {
  if (student.grade < 60) {
    hasFailing = true;
    break;
  }
}

After (declarative)

const hasFailing = students.some(s => s.grade < 60);

Before (manual every check)

let allComplete = true;
for (const task of tasks) {
  if (!task.done) {
    allComplete = false;
    break;
  }
}

After

const allComplete = tasks.every(t => t.done);

6. Use cases

Validation: every field filled

const formFields = [
  { name: "email", value: "alice@example.com" },
  { name: "password", value: "secret123" },
  { name: "username", value: "" },
];

const isFormComplete = formFields.every(field => field.value.trim() !== "");
console.log(isFormComplete); // false — username is empty

Permission checking: user has required role

const userRoles = ["editor", "viewer"];
const requiredRoles = ["editor", "admin"];

// Does user have ANY of the required roles?
const hasAccess = requiredRoles.some(role => userRoles.includes(role));
console.log(hasAccess); // true — "editor" matches

// Does user have ALL required roles?
const hasFullAccess = requiredRoles.every(role => userRoles.includes(role));
console.log(hasFullAccess); // false — missing "admin"

Feature detection

const requiredFeatures = ["localStorage", "fetch", "Promise"];

const allSupported = requiredFeatures.every(feature => feature in window);
if (!allSupported) {
  console.warn("Browser missing required features");
}

Check for duplicates

function hasDuplicates(arr) {
  return arr.some((val, index) => arr.indexOf(val) !== index);
}

hasDuplicates([1, 2, 3, 4]);    // false
hasDuplicates([1, 2, 3, 2]);    // true — 2 appears twice

7. Combining with other logic

!some is equivalent to every (with negated condition)

const nums = [2, 4, 6, 8];

// "None are odd" = "Every one is even"
!nums.some(n => n % 2 !== 0);  // true
nums.every(n => n % 2 === 0);  // true — same result

!every is equivalent to some (with negated condition)

const tasks = [
  { text: "Task 1", done: true },
  { text: "Task 2", done: false },
];

// "Not all done" = "Some are not done"
!tasks.every(t => t.done);  // true
tasks.some(t => !t.done);   // true — same result

8. Real-world examples

Check if any student failed

const students = [
  { name: "Alice", marks: 82 },
  { name: "Bob", marks: 45 },
  { name: "Carol", marks: 91 },
];

const anyFailed = students.some(s => s.marks < 50);
console.log(anyFailed); // true — Bob failed

if (anyFailed) {
  const failures = students.filter(s => s.marks < 50);
  console.log("Failing students:", failures.map(s => s.name));
  // ["Bob"]
}

Validate all inputs have minimum length

const inputs = ["hello", "world", "hi"];

const allValid = inputs.every(input => input.length >= 3);
console.log(allValid); // false — "hi" is too short

Check if array contains a specific item

// some can replace includes when you need a custom comparison
const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
];

const hasAlice = users.some(u => u.name === "Alice");
console.log(hasAlice); // true

// (For primitives, prefer arr.includes(value) instead)

Validate shopping cart

const cart = [
  { name: "Shirt", price: 25, qty: 2 },
  { name: "Pants", price: 50, qty: 1 },
  { name: "Socks", price: 5, qty: 0 },
];

const allHaveQuantity = cart.every(item => item.qty > 0);
console.log(allHaveQuantity); // false — Socks has qty 0

const anyExpensive = cart.some(item => item.price > 40);
console.log(anyExpensive); // true — Pants

Type checking array contents

const values = [1, 2, "three", 4];
const allNumbers = values.every(v => typeof v === "number");
console.log(allNumbers); // false — "three" is a string

const mixed = [1, "hello", true, null];
const hasNull = mixed.some(v => v === null);
console.log(hasNull); // true

9. Performance: short-circuit advantage

Both some and every can be significantly faster than alternatives that always visit every element:

const bigArray = Array.from({ length: 1_000_000 }, (_, i) => i);

// some stops at first match — instant
bigArray.some(n => n === 5); // true (checked only 6 elements)

// filter checks ALL elements, then checks length — wasteful
bigArray.filter(n => n === 5).length > 0; // true (checked 1,000,000 elements)

10. some and every do NOT mutate

Both methods leave the original array untouched and return only a boolean:

const arr = [1, 2, 3];
const result = arr.some(n => n > 2);
console.log(arr);    // [1, 2, 3] — unchanged
console.log(result); // true

Key takeaways

  1. some() returns true if any callback returns truthy — short-circuits on first true.
  2. every() returns true if all callbacks return truthy — short-circuits on first false.
  3. Empty arrays: some([]) is false, every([]) is true (vacuous truth).
  4. Both are more readable than manual loop-and-flag patterns.
  5. Both short-circuit, making them more efficient than filter(...).length > 0.
  6. Use some for existence checks, every for validation / "all must pass" scenarios.

Explain-It Challenge

Explain without notes:

  1. What does [].every(x => x > 0) return, and why?
  2. Why is arr.some(fn) more efficient than arr.filter(fn).length > 0?
  3. Write a one-liner using every to check if all strings in an array are non-empty.

Navigation: ← 1.22.d — forEach() · 1.22.f — slice() and splice() →