JavaScript Array every(callback) method


The every() method in JavaScript is used to test whether all elements in an array pass a specified test implemented by a provided callback function. It returns a boolean value: true if every element satisfies the condition; otherwise, it returns false. This method is useful for validating if all items in an array meet specific criteria.

Syntax:

let result = array.every(callback(element, index, array), thisArg);

Parameters:

  1. callback: A function that is called for each element in the array. It takes three arguments:

    • element: The current element being processed in the array.
    • index (optional): The index of the current element being processed.
    • array (optional): The array every() was called upon.
  2. thisArg (optional): A value to use as this when executing the callback function.

Return Value:

  • A boolean value: true if all elements in the array pass the test; otherwise, false.

Key Points:

  • The every() method does not modify the original array.
  • It stops executing as soon as it finds an element that fails the test, which can make it more efficient than methods that check all elements.
  • It can work on arrays of any data type (numbers, strings, objects, etc.).

Example 1: Basic Usage

const numbers = [2, 4, 6, 8]; const allEven = numbers.every(num => num % 2 === 0); console.log(allEven); // true (all numbers are even)

Example 2: Not All Elements Meet the Condition

const numbers = [2, 4, 5, 8]; const allEven = numbers.every(num => num % 2 === 0); console.log(allEven); // false (5 is not even)

Example 3: Using Objects in an Array

const users = [ { id: 1, isActive: true }, { id: 2, isActive: true }, { id: 3, isActive: false } ]; const allActive = users.every(user => user.isActive); console.log(allActive); // false (not all users are active)

Example 4: Using thisArg

You can use thisArg to specify the value of this inside the callback:

const obj = { threshold: 10, isGreaterThan(value) { return value > this.threshold; } }; const numbers = [11, 12, 15, 9]; const allGreaterThanThreshold = numbers.every(function(num) { return this.isGreaterThan(num); }, obj); console.log(allGreaterThanThreshold); // false (9 is not greater than 10)

Summary:

  • The every() method is a straightforward way to determine if all elements in an array meet a specific condition.
  • It returns true only if every element satisfies the condition defined in the callback function; otherwise, it returns false.
  • This method is particularly useful for validation checks, ensuring that all items in an array conform to expected criteria before proceeding with further operations.