Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript every()

every checks whether all elements in an array satisfy a condition.

It returns true only if every item passes.

Why We Need It

Many validation tasks require confirming all items are valid.

every expresses this clearly and stops early for efficiency.

Syntax

array.every((value, index, array) => condition)

Basic Example

1. All even

const nums = [2, 4, 6];
const allEven = nums.every((n) => n % 2 === 0);

console.log(allEven);

All items match, so result is true.

Real World Example

2. Not all match

const nums = [2, 3, 4];
const allEven = nums.every((n) => n % 2 === 0);

console.log(allEven);

One item fails, so result is false.

Multiple Use Cases

All Must Match

every returns true only if all elements pass the test.

It stops early when it finds a failing element.

Validation

every is great for validation rules like all fields filled.

If you need any match, use some instead.

Empty Arrays

every on an empty array returns true by definition.

Handle this case if it matters.

More Examples

3. Validation

const fields = ["name", "email"];
const valid = fields.every((f) => f.length > 0);

console.log(valid);

Use every to validate all fields.

4. Objects

const users = [{ active: true }, { active: true }];
const allActive = users.every((u) => u.active);

console.log(allActive);

Works with arrays of objects too.

Comparison

Without

let allValid = true;
for (const n of nums) {
  if (n <= 0) {
    allValid = false;
    break;
  }
}

With

const allValid = nums.every((n) => n > 0);

Common Mistakes and Fixes

Using every for any match

Use some when you need at least one match.

Forgetting empty arrays return true

Check array length when needed.

Expecting every to return items

every returns a boolean, not items.

Interview Questions

What does every return on empty arrays?

True.

When should you use every?

When all elements must satisfy a condition.

How is every different from some?

every requires all; some requires any.

Practice Problem

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);

Frequently Asked Questions

What does every return?

A boolean indicating if all items pass the test.

Does every stop early?

Yes, it stops when a failure is found.

What about empty arrays?

every returns true for empty arrays.

Try It Yourself

Try arrays with mixed values to see results.