JavaScript(JS) array method - every
The every()
method is an array method in JavaScript that tests whether all elements in the array pass a specified test. This method returns a boolean value indicating whether all elements pass the test or not.
Here's the syntax of the every()
method:
array.every(callback, thisArg);
array
is the array that theevery()
method is called on.callback
is a function that takes three arguments: the current value of the element being processed, the index of the element being processed, and the array that theevery()
method was called on. This function should return a boolean value indicating whether the element passes the test or not.thisArg
is an optional argument that specifies the value ofthis
inside thecallback
function.
The every()
method iterates through the array and calls the callback
function on each element. If the callback
function returns true
for all elements, the every()
method returns true
. If the callback
function returns false
for any element, the every()
method immediately returns false
without iterating over the remaining elements.
Here's an example of how to use the every()
method:
let array = [1, 2, 3, 4, 5]; let result = array.every(function(element) { return element > 0; }); console.log(result); // true
In this example, we have an array array
containing the elements [1, 2, 3, 4, 5]
. We use the every()
method to test whether all elements in the array are greater than 0. The callback
function checks whether the current element is greater than 0 and returns a boolean value. Since all elements in the array are greater than 0, the every()
method returns true
. The console.log()
statement outputs the value of result
, which is true
.
Note that the every()
method stops iterating over the array as soon as it encounters an element for which the callback
function returns false
. Also, the every()
method was introduced in ECMAScript 5, so it may not be supported by older browsers.