The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
The syntax of Array.every() method is:
every(callbackfn: function, thisArg?: any): boolean
This every() method of Array determines whether all the members of an array satisfy the specified test.
Parameter | Optional/Required | Description |
---|---|---|
callbackfn | required | A function to test for each element, taking three arguments: the current element, the index of the current element, and the array being traversed. |
thisArg | optional | Value to use as this when executing callbackfn. |
Array.every() returns value of type boolean
.
The every() method can be used to check if all elements in an array are positive numbers.
For example,
arr
with numeric values [1, 2, 3, 4, 5].every(callbackfn)
to test if all elements in the array are positive.result
.result
to the console.const arr = [1, 2, 3, 4, 5];
const result = arr.every(num => num > 0);
console.log(result);
true
The every() method can be used to check if all elements in an array are strings.
For example,
arr
with string values ['apple', 'banana', 'cherry'].every(callbackfn)
to test if all elements in the array are strings.result
.result
to the console.const arr = ['apple', 'banana', 'cherry'];
const result = arr.every(val => typeof val === 'string');
console.log(result);
true
The every() method can be used to check if all elements in an array are even numbers.
For example,
arr
with numeric values [2, 4, 6, 8, 10].every(callbackfn)
to test if all elements in the array are even.result
.result
to the console.const arr = [2, 4, 6, 8, 10];
const result = arr.every(num => num % 2 === 0);
console.log(result);
true
In this TypeScript tutorial, we learned about every() method of Array: the syntax and few working examples with output and detailed explanation for each example.