The every() method of the Array class in JavaScript tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
There are 2 variations for the syntax of Array.every() method. They are:
every(callbackFn)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to test each element in the array. It takes three arguments: element, index, and array. |
This method returns true if every element in the calling array satisfies the testing function.
Returns value of type Boolean
.
every(callbackFn, thisArg)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to test each element in the array. It takes three arguments: element, index, and array. |
thisArg | optional | A value to use as this when executing callbackFn. |
This method returns true if every element in the calling array satisfies the testing function, using thisArg as the value of this inside callbackFn.
Returns value of type Boolean
.
In JavaScript, we can use the every() method to check if all elements in an array are greater than a specified value.
For example,
const arr = [10, 20, 30, 40, 50];
const isGreaterThanFive = element => element > 5;
const result = arr.every(isGreaterThanFive);
console.log(result);
true
We can use the every() method to check if all elements in an array are strings.
For example,
const strArr = ['apple', 'banana', 'cherry'];
const isString = element => typeof element === 'string';
const result = strArr.every(isString);
console.log(result);
true
We can use the every() method with a thisArg to test all elements in an array using a specific context.
For example,
const arr = [1, 2, 3, 4, 5];
const context = { threshold: 4 };
function isLessThanThreshold(element) {
return element < this.threshold;
}
const result = arr.every(isLessThanThreshold, context);
console.log(result);
false
In this JavaScript tutorial, we learned about every() method of Array: the syntax and few working examples with output and detailed explanation for each example.