How To Check If an Array Is Empty or Exists in JavaScript – Definitive Guide

Before accessing the array elements using its index, you need to confirm whether the array is empty or exists.

You can check if an array is empty or exists in JavaScript using the if (Array.isArray(myArray) && myArray.length) statement.

Basic Example

var myArray = [];

if (Array.isArray(myArray) && myArray.length) {
  console.log('Array exists and not empty');
}

This tutorial teaches you how to check if an array is empty or exists in JavaScript.

Using IsArray And Length

The isArray() method checks if the passed object is an array object.

To check if an array is empty or element exists in it,

  • use the static method array.isArray() to check if the object is an array
  • Use the .length property of the array to check the length of the array. If the length is not 0, items exist in that array.

Use this method if you want to use the modern method available in ES5+.

Code

var myArray = [];

if (Array.isArray(myArray) && myArray.length) {
  console.log('Array exists and not empty');
}

Using Typeof and Length

The typeof operator determines the type of an object.

To check if an array object exists and is not empty,

  • Check if the type of the object is not equal to undefined
  • Check the length of the array using the .length property. If the length is greater than 0, element(s) exists in the array

Code

var myArray = [‘a’ ];

if (typeof myArray !== 'undefined' && myArray.length == 0) {
  // Array exists but is empty.
} else if (typeof myArray !== 'undefined' && myArray.length > 0) {
  console.log('Array exists and not empty');  // "Array exists and not empty"
}

Using jQuery isEmptyObject Method

The jQuery isEmptyObject() method checks if the passed object is empty or contains any iterable value in it.

To check if an array exists and is not empty,

  • Use the single isEmptyObject() method. It checks if the object is any type of collection and contains objects.

Code

var myArray = [];

if (jQuery.isEmptyObject(myArray)) {
  console.log('Array exists and empty');
}

var mynonEmptyArray = ['a'];

if (!jQuery.isEmptyObject(mynonEmptyArray)) {
  console.log('Array exists and not empty');
}

Using Lodash isArray Method

The lodash library provides many useful methods to perform various operations with a modular approach and better performance practices.

To check if the array exists and is not empty,

  • Use the isArray() method to check if the object is of type Array
  • Use the isEmpty() method to check if the array contains any element in it

Code

var myArr= [1,2,3];

if(_.isArray(myArr) && !_.isEmpty(myArr)){
   console.log('Array exists and not empty');
}

Additional Resources

Leave a Comment