javascript

Methods to check empty array using javascript

To check where an array is empty or not you can use below methods

// First method
const my_array = []

if (Array.isArray(my_array) && my_array.length) {
    //Array is not empty
} else {
    // Array is empty
}

// Second Method
if (my_array !== undefined && my_array.length > 0) {
    // Do somethong
}

Here, we are checking the array variable my_array if it is empty or not. In the first method, we are using Array.isArray() method along with the Array.length property.

In the second method, we are checking if the array is not undefined and has a length greater than 0.

Was this helpful?