JavaScript every: The Complete Guide

JavaScript every() method executes the provided callback function once for each element present in the array until it finds one that returns a false value. 

JavaScript every

JavaScript every() is a built-in array function that tests whether all elements in an array pass the test implemented by the provided function. If you have a specific condition that needs to be checked on all elements of the array, then you can use the array every() function.

Syntax

The syntax of the array every() function is the following.

array.every(function(currentValue, index, arr), thisValue)

Parameters

The callback function is invoked with the three arguments: a value of the element, an index of the element, and the Array object being traversed.

currentValue: It is required, and it is the value of the current element.

index: It is Optional. The array index of the current element.

arr: Optional. The array object to the current element belongs.

thisValue: Optional. A value to be passed to the function to be used as its “this” value. If this parameter is empty, the value “undefined” will be passed as its “this” value.

If a thisValue parameter is provided to every, it will be used as a callback’s this value. Otherwise, the value undefined will be used as this value.

See the following example.

// app.js

let arr = [1, 11, 21, 31, 41]

const diff = (currentValue) =>  currentValue < 51

console.log(arr.every(diff))

In the above example, the array contains the five elements.

Now, in the javascript array, every function takes one callback function. The callback function is a diff function, which takes the currentValue of the array and checks the condition, which is < 51.

If all the elements are under 51, it returns true. Otherwise, it will give us a false output. Here, also we have used the arrow function.

See the output below.

Javascript Array Every Example | Array.prototype.every() Tutorial

Let’s change one element of an array to 61 and test the output.

// app.js

let arr = [1, 11, 21, 31, 61]

const diff = (currentValue) =>  currentValue < 51

console.log(arr.every(diff))

So, here the last element of an array is higher than 51. So, the output will be false.

Array.prototype.every() Tutorial

That’s it for this tutorial.

See also

Javascript array from()

Javascript array values()

Javascript array includes()

Javascript array lastIndexOf()

Javascript array indexOf()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.