TypeScript Array every()
Syntax & Examples
Array.every() method
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
Syntax of Array.every()
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.
Parameters
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. |
Return Type
Array.every() returns value of type boolean
.
✐ Examples
1 Using every() to test if all elements are positive
The every() method can be used to check if all elements in an array are positive numbers.
For example,
- Create an array
arr
with numeric values [1, 2, 3, 4, 5]. - Define a callback function that checks if a number is positive.
- Use
every(callbackfn)
to test if all elements in the array are positive. - Store the result in
result
. - Log
result
to the console.
TypeScript Program
const arr = [1, 2, 3, 4, 5];
const result = arr.every(num => num > 0);
console.log(result);
Output
true
2 Using every() to test if all elements are strings
The every() method can be used to check if all elements in an array are strings.
For example,
- Create an array
arr
with string values ['apple', 'banana', 'cherry']. - Define a callback function that checks if a value is a string.
- Use
every(callbackfn)
to test if all elements in the array are strings. - Store the result in
result
. - Log
result
to the console.
TypeScript Program
const arr = ['apple', 'banana', 'cherry'];
const result = arr.every(val => typeof val === 'string');
console.log(result);
Output
true
3 Using every() to test if all elements are even
The every() method can be used to check if all elements in an array are even numbers.
For example,
- Create an array
arr
with numeric values [2, 4, 6, 8, 10]. - Define a callback function that checks if a number is even.
- Use
every(callbackfn)
to test if all elements in the array are even. - Store the result in
result
. - Log
result
to the console.
TypeScript Program
const arr = [2, 4, 6, 8, 10];
const result = arr.every(num => num % 2 === 0);
console.log(result);
Output
true
Summary
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.