How to use every() Method In Typescript

The approach uses the every() method, which tests all elements of the array that are passed in the condition. If the conditions are satisfied, then the true result is been returned otherwise, the false result is been returned.

Syntax:

array.every(
callback(element: ElementType, index: number, array: ElementType[])
=> boolean): boolean;

Example: The below code explains the use of the every() method to check if an array is empty or not.

Javascript




const array1: number[] = [];
const array2: number[] = [1, 2, 3];
 
function checkEmpty(arr: any[]) {
    const res = arr.every(item => false);
    if (res) {
        console.log(`Array: ${arr}, is empty!`);
    }
    else {
        console.log(`Array: ${arr}, is not empty!`);
    }
}
 
checkEmpty(array1);
checkEmpty(array2);


Output:

Array: , is empty!
Array: 1,2,3, is not empty!

Check if an Array is Empty or not in TypeScript

In TypeScript, while performing any operation on the array, it is quite important that there should be elements or data in the array, else no operation can be done. We can check whether the array contains the elements or not by using the below-listed methods:

Table of Content

  • Using length Property
  • Using every() Method
  • Using filter() method

Similar Reads

Using length Property

This approach uses the length property which is a built-in property in Typescript. This property returns the number of elements in the array....

Using every() Method

...

Using filter() method

The approach uses the every() method, which tests all elements of the array that are passed in the condition. If the conditions are satisfied, then the true result is been returned otherwise, the false result is been returned....