How to check if an array is empty in JavaScript

#javascript #array

Last updated on Nov 18, 2020 by Suraj Sharma



In this tutorial, you will learn the easiest way to find whether a given JavaScript array is empty or not


The simplest way to check for an empty array is to check for it’s length property


Example:



const arr = []

arr.length <= 0 // true

const anotherArr = [1.2]

anotherArr.length <= 0 // false


If the array.length is zero, that means the array is empty


To be on the safer side you should always check if the given value is an array, by using the Array.isArray() method


So your final condition would look like this



function isArrayEmpty(value) {
  if (Array.isArray(value)) {
    return value.length <= 0;
  } else {
    throw new Error('value is not an Array');
  }
}

isArrayEmpty([]); // true

isArrayEmpty([1,2,3]) // false

isArrayEmpty('array'); // 'Error: value is not an Array'


Related Solutions



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.