javascript
  1. javascript-every

JavaScript every() Method

The every() method is used to test whether all elements in an array pass the test implemented by the provided function. It returns true if the callback function returns a truthy value for every array element. Otherwise, it returns false.

Syntax

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

array.every(function(currentValue, index, arr), thisValue)
  • currentValue: The current element being processed in the array.
  • index (Optional): The index of the current element being processed in the array.
  • arr (Optional): The array that every() is being applied upon.
  • thisValue (Optional): A value to use as this while executing the callback function.

Example

Here's an example that uses the every() method to check if all values in an array are even:

const numbers = [2, 4, 6, 8];

const allEven = numbers.every(function(num) {
  return num % 2 === 0;
});

console.log(allEven); // true

Output

The code above will output true because all values in the numbers array are even.


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Every Function Example</title>
</head>
<body>

<!-- Display the result in this element -->
<div id="result"></div>

<script>
  // Sample array of numbers
  const numbers = [2, 4, 6, 8];

  // Use the every function to check if all numbers are even
  const allEven = numbers.every(function(num) {
    return num % 2 === 0;
  });

  // Display the result on the page
  const resultElement = document.getElementById('result');
  resultElement.innerHTML = `<p>Are all numbers even? ${allEven ? 'true' : 'false'}</p>`;
</script>

</body>
</html>
Try Playground

Explanation

The every() method executes the provided function once for each element in the array until it finds an element for which the callback function returns a falsy value. If such an element is found, the iteration is stopped and false is returned. If the callback function returns truthy for every element, the function will return true.

Use

The every() method is useful for verifying that all elements in an array satisfy certain criteria. It is often used in conjunction with anonymous functions or arrow functions to perform more complex checks.

Important Points

  • The every() method does not mutate the original array.
  • If the array is empty, every() returns true.
  • The callback function is not executed for array elements without values.
  • If thisValue is provided, it is used as this when executing the callback function.

Summary

The every() method is an array method that returns true if the provided function returns true for every element in the array. It is useful for verifying that all elements in an array satisfy certain criteria.

Published on: