JavaScript Array every()

JavaScript Array every()

The JavaScript Array.prototype.every() method is used to test if all elements in an array pass a certain condition. It iterates over each element of the array and checks it against a provided condition. If all elements pass the condition, the every() method returns true. If any element does not pass the condition, the every() method returns false.


// Example:

let numbers = [1, 2, 3, 4, 5];

let result = numbers.every(num => num > 0);

console.log(result); // true
    

In the example above, the every() method is used to check if all elements in the numbers array are greater than 0. Since all elements in the array are greater than 0, the every() method returns true.

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


array.every(callback(currentValue, index, array), thisArg);
    

Where the callback is a function to test for each element. It takes three arguments:

  • currentValue: 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.

The thisArg is an optional parameter which defines the value of this inside the callback function.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe