How to check if an Array is Empty in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 06 20212 min read

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 the holding 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.

To be extra safe, if you're unsure if the arr variable holds an array you can check for the type of the value stored in it.

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 have used the && (and) operator to signify that both conditions have to be true for the if block to run.

We first check if the arr 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 if arr is set to a string. Strings in javascript also have a length property.
  • it's supported in Internet Explorer versions 9-11.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee