every()
is a built-in method we can use with the Array
type in JavaScript.
The following is the method prototype:
Array.every(function(currentValue, index, arr), thisValue)
The method takes the following input parameters:
function
: This is the callback function that implements a specific condition.
currentValue
: The value of the current element being processed in the array.
index
: The index of the current element. This parameter is optional.
arr
: The array for which the every()
function is called. This parameter is optional.
thisValue
: A value to be passed to the method as the this
value of the callback function. This parameter is optional.
The every()
method executes the callback function for each element of the array. If the callback function returns false
, the every()
method also returns false
and does not evaluate any remaining elements.
If the callback function returns true
for all elements of the array, the every()
method also returns true
, meaning that every element within the array meets the specified condition.
Suppose you have an array of n elements and you want to check if all of the elements are greater than 10. Such tasks can typically be completed using for
loops.
The every()
method offers the same functionality but without the use of cumbersome loops.
The every()
method is used to check if all of the elements within an array meet a specified condition.
The condition is implemented in the form of a callback function. This makes the code concise and easier to read.
// define an arrayvar arr = [5, 3, 1, 9, 7];// define callback functionfunction isPositive(currentValue){return currentValue > 0;}// printing the resultconsole.log("Array contains all positive numbers: " + arr.every(isPositive));// define callback functionfunction isEven(currentValue){return (currentValue % 2 === 0);}// printing the resultconsole.log("Array contains all even numbers: " + arr.every(isEven));// define embedded callback functionvar result = arr.every(function(currentValue){return (currentValue % 2 !== 0);})// printing the resultconsole.log("Array contains all odd numbers: " + result);
In the above example, we begin by declaring an array of 5 random numbers.
Then we define our first callback function (isPositive
) that only takes the currentValue as input. The function checks whether the array contains all positive numbers. As our array does contain only positive numbers, the every()
method returns true
.
Moving on, we define a second callback function (isEven
). The function checks whether the currentValue is even. As our array contains no even numbers, the every()
method returns false
.
Finally, we define a third callback function. This time, we have embedded the callback function within the every()
method call. This means that we can skip out on giving our callback function a name. The function checks whether the array contains all odd numbers. As our array does contain only odd numbers, the every()
method returns true
.
Free Resources