Close full mode

TypeScript array every method definition and examples

TypeScript array every method example:

every method is used to check if every element of an array satisfies a given condition. This method is defined in JavaScript arrays and we can use it in TypeScript as well.

In this post, we will learn how to use every method with examples.

Definition of every:

every method is defined as like below:

every(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;

This method takes two parameters:

  • predicate is a function. It can be an arrow function or a callback function.
    • This function takes up to three elements. The first one is the value it is iterating, the second one is the index of the value, and the third one is the array.
    • This function will keep running until it returns a false value. If it returns true for all elements, then it will run till the end of the array.
  • thisArg is an optional value. This is an object to which this can refer in the function. If we don't pass this, it will be undefined.

Return value of every:

This method returns one boolean value. It returns true if the predicate function returns true for all elements. Else it returns false.

Example of every:

Let's try every with an example:

let arr: number[] = new Array(1, 2, 3, 4, 5, 6);
let result: boolean = arr.every((e: number) => {
return e % 2 == 0
result ? console.log('All numbers are even !') : console.log('All numbers are not even !');

In this example,

  • arr is the given number array
  • The every method is checking if all elements are even or not.
  • The return value is stored in result, which is a boolean value.
  • Based on the return value, we are printing a message.

If you run this example, it will print:

All numbers are not even !

Example with objects:

Let's try with an array of objects. We can create a type alias to define the type of objects we are using in the array.

For example,

type studentType = { name: string, age: number };
let arr: studentType[] = new Array({ name: 'Alex', age: 12 }, { name: 'Bob', age: 11 }, { name: 'Ela', age: 12 });
let result: boolean = arr.every((e: studentType) => {
return e.age > 10
result ? console.log('All students are elder than 10 years') : console.log('All students are not elder than 10 years !');
  • studentType is the type of objects we are adding in the array.
  • The every method checks if the age of all objects are greater than 10 or not. If yes, it will return true.
  • The return value of every is stored in result.
  • Based on the value of result, we are printing one message.

It will print:

Typescript array every
Typescript array every

Subscribe to our Newsletter

Check if an element is in an array or not in TypeScript
Typescript extract a section of an array using slice