Onjsdev

Share


Javascript every method

JavaScript Every Method


By onjsdev

Feb 7th, 2024

Javascript every method determines whether all elements in an array pass a test implemented by a provided callback function. It returns a boolean value: true if all elements pass the test, false otherwise.

Syntax

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

array.every(callback, thisArg);

The callback function is called for each element in the array and takes three parameters:

  • element: The current element being processed.
  • index (optional): The index of the current element in the array.
  • array (optional): The array that every was called upon.

Examples

In this example, we have an array of numbers, and we want to check if all the numbers in the array are equal:

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

const allEqual = numbers.every(number => number  === numbers[0]);

console.log(allEqual); // False

here, the callback function checks if the current element (number) is equal (==) to the first element of the array (numbers[0]).

Since the last element of the array (4) is not equal to the first element (2), the every method returns false, and the variable allEqual is assigned the value false.

Key points

While working with the javascript every method it is good to know that:

  • The callback should return a boolean value (true or false).
  • The every method stops iterating as soon as the callbackFn returns false for an element.
  • It returns true for empty arrays (because all elements vacuously pass any test).

Conclusion

In conclusion, the javascript every method is a useful and powerful tool in for testing whether all elements in an array pass a particular test. It allows us to quickly and easily check if all elements in an array satisfy a condition, without having to write complex loops and if statements.

If you want to learn more about javascript array methods, you can check the following articles:

Thank you for reading.