Open In App

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:

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.

Syntax:

myArray.length;

Example: The below example uses the length property to check whether the passed array is empty or not.






const array1: number[] = [];
const array2: number[] = [1, 2, 3];
 
function checkEmpty(arr: any[]) {
    const res = (arr.length === 0);
    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!

Using every() 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.

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.




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!

Using filter() method

This approach uses the filter() method, which checks that the input array is empty by filtering elements and then comparing the result of the array length to the zero.

Syntax:

array.filter(callback(element[, index[, array]])[, thisArg]);

Example: The below code uses the filter() method to check if the passed array is empty ot not.




const array1: number[] = [];
const array2: number[] = [1, 2, 3];
 
function checkEmpty(arr: any[]) {
    const res =
        arr.filter(item => true).length === 0;
    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!

Article Tags :