While working with arrays in javascript, often there is a requirement to check if an array is empty or not. This article will describe how to check if an array is empty or exists in javascript.

Table of Contents:-

Check if array is empty using isArray() and length property

Javascript’s isArray() method checks if the passed in argument value is an array or not.

Example:-

Check if the below arrays are empty or not

  • [“Javascript”, “Is”, “Popular”,”Language”]
  • [ ]

Function Code:-

function checkIfArrayEmpty(_array)
{
if (Array.isArray(_array) && _array.length) {
    console.log("Array Is Not Empty");
}
else
{
    console.log("Array Is Empty");
}
}

Function Code:-

let array1 = ["Javascript", "Is", "Popular","Language"];
let array2 = [ ];
checkIfArrayEmpty(array1);
checkIfArrayEmpty(array2);

Output:-

Array Is Not Empty
Array Is Empty

Explanation:-

  • Here, within the if statement, the first check is applied to find out if the passed in value is an array. Once the first check is passed, the code will perform the second check to see if the array’s length is greater than zero.
  • If both the conditions are true, “Array Is Not Empty” is printed on the console, else “Array Is Empty” is printed.

Check if array is empty by checking if array is undefined and different operations on length

Example:-

Check if the below arrays are empty or not

  • [“Javascript”, “Is”, “Popular”,”Language”]
  • [ ]

Function Code:-

function checkIfArrayEmpty(_array)
{
if (typeof _array != "undefined" && _array != null && _array.length != null && _array.length > 0)
    {
    console.log("Array Is Not Empty")
    }
else
{
    console.log("Array Is Empty or Undefined")
}
}

Function Code:-

let array1 = ["Javascript", "Is", "Popular","Language"];
let array2 = [ ];
checkIfArrayEmpty(array1);
checkIfArrayEmpty(array2);

Output:-

Array Is Not Empty
Array Is Empty or Undefined

Explanation:-

  • Here, within the if statement, four checks are applied:
    • If the array is not undefined
    • If the array is not null
    • If the array’s length is not equal to null
    • If the array’s length is greater than zero.
  • All these checks verify if the array exists and if yes, then it’s not empty.
  • If all the conditions are true, only then, “Array Is Not Empty” is printed on the console. Otherwise, if any of the conditions is false, “Array Is Empty or Undefined” is printed on the console.

Read More:

I hope this article helped you to check if an array is empty or not in javascript. Good Luck !!!