JavaScript Array every(callback) method
The every()
method in JavaScript is used to test whether all elements in an array pass a specified test implemented by a provided callback function. It returns a boolean value: true
if every element satisfies the condition; otherwise, it returns false
. This method is useful for validating if all items in an array meet specific criteria.
Syntax:
Parameters:
callback
: A function that is called for each element in the array. It takes three arguments:element
: The current element being processed in the array.index
(optional): The index of the current element being processed.array
(optional): The arrayevery()
was called upon.
thisArg
(optional): A value to use asthis
when executing the callback function.
Return Value:
- A boolean value:
true
if all elements in the array pass the test; otherwise,false
.
Key Points:
- The
every()
method does not modify the original array. - It stops executing as soon as it finds an element that fails the test, which can make it more efficient than methods that check all elements.
- It can work on arrays of any data type (numbers, strings, objects, etc.).
Example 1: Basic Usage
Example 2: Not All Elements Meet the Condition
Example 3: Using Objects in an Array
Example 4: Using thisArg
You can use thisArg
to specify the value of this
inside the callback:
Summary:
- The
every()
method is a straightforward way to determine if all elements in an array meet a specific condition. - It returns
true
only if every element satisfies the condition defined in the callback function; otherwise, it returnsfalse
. - This method is particularly useful for validation checks, ensuring that all items in an array conform to expected criteria before proceeding with further operations.