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

ParameterOptional/RequiredDescription
callbackfnrequiredA function to test for each element, taking three arguments: the current element, the index of the current element, and the array being traversed.
thisArgoptionalValue 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,

  1. Create an array arr with numeric values [1, 2, 3, 4, 5].
  2. Define a callback function that checks if a number is positive.
  3. Use every(callbackfn) to test if all elements in the array are positive.
  4. Store the result in result.
  5. 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,

  1. Create an array arr with string values ['apple', 'banana', 'cherry'].
  2. Define a callback function that checks if a value is a string.
  3. Use every(callbackfn) to test if all elements in the array are strings.
  4. Store the result in result.
  5. 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,

  1. Create an array arr with numeric values [2, 4, 6, 8, 10].
  2. Define a callback function that checks if a number is even.
  3. Use every(callbackfn) to test if all elements in the array are even.
  4. Store the result in result.
  5. 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.