JavaScript Array Method: every()

Java Script @ Freshers.in

JavaScript arrays provide a plethora of methods to manipulate and analyze their elements effectively. Among these methods, every() stands out as a powerful tool for determining whether all elements in an array satisfy a given condition. In this article, we’ll delve into the every() method, examining its syntax, functionality, and usage through comprehensive examples.

Syntax:

The syntax of the every() method is straightforward:

array.every(callback[, thisArg])

Parameters:

  • callback: A function to test each element of the array. It should return true if the element passes the test, otherwise false.
  • thisArg (optional): An optional object to be used as this when executing the callback function.

Return Value:

  • true if the callback function returns true for every element in the array; otherwise, false.

Examples:

Let’s explore the every() method with detailed examples:

Example 1:

let numbers = [1, 2, 3, 4, 5];
let allEven = numbers.every((num) => num % 2 === 0);
console.log(allEven); // Output: false

In this example, the every() method is used to check if all elements in the numbers array are even. Since not all elements are even, the result is false.

Example 2:

let ages = [25, 30, 42, 50, 28];
let allAdults = ages.every((age) => age >= 18);
console.log(allAdults); // Output: true

Here, the every() method is employed to determine if all elements in the ages array represent adults (ages 18 and above). Since all elements meet this condition, the result is true.

Example 3:

let temperatures = [-5, 10, 15, 20];
let allPositive = temperatures.every((temp) => temp >= 0);
console.log(allPositive); // Output: false

In this example, the every() method is utilized to check if all elements in the temperatures array are positive. Since there is a negative temperature, the result is false.

Author: user