Javascript Array every()

The JavaScript Array every() method checks if all the array elements pass the given test function.

The syntax of the every() method is:

arr.every(callback(currentValue), thisArg)

Here, arr is an array.


every() Parameters

The every() method takes in:

  • callback - The function to test for each array element. It takes in:
    • currentValue - The current element being passed from the array.
  • thisArg (optional) - Value to use as this when executing callback. By default, it is undefined.

Return value from every()

  • Returns true if all array elements pass the given test function (callback returns a truthy value).
  • Otherwise, it returns false.

Notes:

  • every() does not change the original array.
  • every() does not execute callback for array elements without values.

Example: Check Value of Array Element

function checkAdult(age) {
    return age >= 18;
}

const ageArray = [34, 23, 20, 26, 12];
let check = ageArray.every(checkAdult); // false

if (!check) {
    console.log("All members must be at least 18 years of age.")
}

// using arrow function
let check1 = ageArray.every(age => age >= 18); // false
console.log(check1);

Output

All members must be at least 18 years of age.
false

Recommended Reading: JavaScript Array some()