Anjan Dutta

How to check if a javascript array is empty or not

How to check if a javascript array is empty or not

Using the .length property we can check if a javascript array is empty or not.

Before checking for an empty array, we must check if the given variable is an Array or not.

If it's an array then we will proceed for a further check, otherwise, we have to terminate our check and return the result.

See the below code example, here we have written the solution in a functional programming way.

var arr = [10, 20];
function checkIfArray(t) {
if (Array.isArray(t) && t.length) {
console.log('Array is not empty');
} else {
console.log('Either not an array or is empty');
}
}
// scenario one
checkIfArray(arr);
// > Array is not empty
// scenario two
let num = 20;
checkIfArray(num);
// > Either not an array or is empty

In the above example, we have created the function checkIfArray() and tested it for two scenarios.

Inside the function body, there is this condition

if (Array.isArray(t) && t.length).

The first part of the condition Array.isArray is checking if the passed variable is an Array or not.

The second part t.length is checking if the given array has a length greater than zero.

This way we are checking both the conditions to test if an array in javascript is empty or not using .length function.