JavaScript Every() method

The every() method in JavaScript is used to check if all elements in an array pass a certain condition. It returns a boolean value, true if all elements satisfy the condition, and false if at least one element fails the condition.

The syntax for the every() method is as follows:

array.every( callback( element, index, array ), thisArg )

  • callback: Function is required. It is called for each element in the array, taking three arguments:

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

This example checks whether all elements in the ages array are over 20. The isOverTwenty() callback function returns true if the current element is over 20, and false otherwise. The every() method returns false because one of the elements in the ages array, 16, is not over 20.

 
const ages = [ 32, 33, 16, 40 ];
 
function isOverTwenty(age) {
 return age > 20;
}
 
const areAllOver20 = ages.every(isOverTwenty);
 
console.log(areAllOver20); // false
 

Using thisArg to specify a context

Here, thisArg is used to provide a context object for the isPositive function. The function checks if each element is greater than 0, and the result is true.

 
const contextExample = [ 1, 2, 3, 4, 5 ];
function isPositive(num) {
 return num > 0;
}
const allPositiveWithContext = contextExample.every(isPositive, {
 max : 10
});
console.log(allPositiveWithContext); // Output: true
 
 

Checking if all elements are truthy

In this example, the every() method checks if all elements in the mixedValues array are truthy by passing the Boolean function as the callback. The result is false because the null element is falsy.

 
const mixedValues = [ true, 42, 'hello', null ];
const allTruthy = mixedValues.every(Boolean);
console.log(allTruthy); // Output: false
 
 

This example checks whether all elements in the students array are passing students. The isPassingStudent() callback function returns true if the current student's grade is 70 or higher, and false otherwise. The every() method returns true because all students in the students array have a grade of 70 or higher.

 
 
const students = [
  { name: "John", grade: 90 },
  { name: "Mary", grade: 85 },
  { name: "Peter", grade: 75 },
];
 
function isPassingStudent(student) {
  return student.grade >= 70;
}
 
const areAllPassingStudents = students.every(isPassingStudent);
 
console.log(areAllPassingStudents); // true
 
 

 Check if all elements have a property

 
const persons = [
  { name: 'John', age: 25 },
  { name: 'Alice', age: 30 },
  { name: 'Bob' }
];
 
const allHaveAge = persons.every(function(person) {
  return 'age' in person;
});
 
console.log(allHaveAge); // Output: false