How to check if an Array is Empty in JavaScript

avatar

Borislav Hadzhiev

Mon Apr 25 20222 min read

Updated - Mon Apr 25 2022

Check if an Array is Empty in JavaScript #

To check if an array is empty access its length property, e.g. arr.length. If an array's length is equal to 0, then it is empty. If the array's length is greater than 0, it isn't empty.

index.js
const arr = ['hello']; if (arr.length > 0) { // if this code block runs // 👉️ arr is not empty console.log('arr is not empty') }

The if block will only run if the array's length is greater than 0. If the array's length is greater than zero it contains at least 1 element.

Alternatively, you can use optional chaining operator ?. to avoid an error if variable storing the array is set to undefined or null.

index.js
// Not supported in IE 6-11 const arr = ['hello']; // 👇️ Use ?. if (arr?.length > 0) { // if this code block runs // 👉️ arr is not empty console.log('arr is not empty') }

This code snippet is different from the first one because even if the arr variable was set to undefined or null we wouldn't get an error when we try to access the length property on the array.

index.js
let arr = undefined; if (arr?.length > 0) { // if this code block runs // 👉️ arr is not empty }
You can think of the optional chaining operator as a safe way to access properties. If it encounters an undefined or null value it just short-circuits and returns undefined, instead of throwing an error.

If you're unsure whether the variable stores an array, you can check for the type of its value before accessing its length property.

index.js
let arr = ['hello']; if (Array.isArray(arr) && arr.length > 0) { // if this code block runs // 👉️ arr is not empty console.log('arr is not empty') }

We have 2 conditions in the if statement. We used the && (and) operator to signify that both conditions have to be satisfied for the if block to run.

We first check if the arr variable stores an array and then check if the array's length is greater than 0.

This approach is similar to the optional chaining one, but I prefer it because:

  • the optional chaining approach doesn't account for the case when arr is set to a string. Strings in javascript also have a length property.
  • it's supported in Internet Explorer versions 9-11.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.