How to check if an array is empty in JavaScript

In this tutorial, we’re going to look at how to check if an array is empty in JavaScript. We’re going to start with the simplest method of using the ‘length’ property, but we’re not going to stop there.

We’re also going to be looking at various other pre-defined array methods, including those that work alone and those that need the help of a loop

Use the length property to check if an array is empty

As I mentioned in the introduction, the array ‘length’ property can be used to determine if an array is empty or not. This property returns the number of elements (indices) an array currently has.

If the length is 0, then we have an empty array in our hands. It’s as simple as that.

let arr = [];

if(arr.length === 0) {
    console.log('Array is empty');
}
else {
    console.log('Array is not empty');
} 

isArray and length property

Though checking the length of the array is a great way of determining if it’s empty or not, it’s not a foolproof method. Why is that?
Well, the ‘length’ property works on both arrays and strings.

let arr = [];
let str = '';
console.log(arr.length === 0); //true - empty
console.log(str.length === 0); //true - empty 

As you can see in the example above, both empty strings and arrays return a length of 0 when they’re empty, which means just checking for the length of an array will give us a lot of false positives.

So, it’s always best to check if an array is actually an array first.

There are different ways to determine if a variable is an array, but the most efficient one is by using the Array.isArray() method.

The isArray method was especially created for this purpose, and it doesn’t produce any false positives or negatives. Send the variable you want to check as its argument, and it’ll return ‘true’ if the value assigned to a variable is an array, and false otherwise, as shown below:

if(arr.length === 0 && Array.isArray(arr)) {
    console.log('Array is empty');
}
else {
    console.log('Array is not empty or you have not entered a valid array');
} 

Now, if the value of arr is [], that is, if it’s an empty array, the console will print ‘Array is empty’.

If its value is ‘’, that is, an empty string, it’ll print ‘Array is not empty, or you have not entered a valid array’.
Our program works perfectly now!

Typeof and length property

Even though isArray is a straightforward way of finding if a variable contains an array, you can still use the trusty ‘typeof’ method to arrive at the same result.

Before we use this method though, I need to warn you. When using ‘typeof’ on an array, you don’t get back ‘array’ as its type, you actually get back ‘object’. This means the type of both arrays and objects are the same.

console.log(typeof arr); //object 

Now, this would be an issue in any other case, but not in ours. Why is that? Well, we’re not just checking for the type. We’re also checking for the length of the variable.

And the ‘length’ property only works on strings and arrays, and not on objects. If you use ‘length’ on an object, empty or otherwise, you’ll get back an ‘undefined’ and nothing else, so our condition will always return ‘false’, as shown below:

let obj = {};
console.log(typeof obj); //object
console.log(obj.lenght); //undefined 

So, instead of using the isArray() method, we can use the ‘typeof’ method since even if the type is ‘object’, the ‘length’ property should also be valid, or the condition will return falsle, as shown below:

console.log(obj.length === 0 && typeof obj === 'object'); //false - always false when 'length' is used 

So, now that you know that objects won’t create false positives on our program, let’s design our condition properly:

function isEmptyArray(arr) {
  if(arr.length === 0 && typeof arr === 'object') {
    return 'Empty array';
  }
  else {
    return 'Not an empty array, or not an array';
  }
}

console.log(isEmptyArray([])); //Empty array
console.log(isEmptyArray([1,2,3])); //Not an empty array, or not an array
console.log(isEmptyArray('')); //Not an empty array, or not an array
console.log(isEmptyArray({})); //Not an empty array, or not an array 

Look at that! We don’t have to worry about false positives or negatives anymore.

Use the ternary operator instead

Instead of using the ‘if else’ condition structure, you can use the ‘ternary’ operator and save some time and lines of code as shown below:

function isEmptyArray(arr) {
  return (arr.length === 0 && typeof arr === 'object') ? 'Empty array' : 'Not an empty array, or not an array';
} 

Using pre-defined methods

There are a few pre-defined JavaScript methods that can be used to check if an array is empty. Let’s look at some of the common ones in this section.

Join() method

As the name implies, the ‘join’ method is used to join an array into a string. Every element will become a part of the string (character/word), and they’ll be concatenated with the join condition.

For example, if you have an array with single character elements like this, [‘a’,’b’,’c’], and you use an empty string as the join condition, you’ll end up with a string like this: ‘abc’.

So, to check if our array is empty, we can use the join method with an empty string as the join condition, and then check if the resultant string is an empty string, as shown below:

function isArrayEmpty(arr) {
  if(arr.join('') === '') {
    return 'Empty array';
  }
  else {
    return 'Not an empty array';
  }
}

console.log(isArrayEmpty([1,2,3])); //Not an empty array
console.log(isArrayEmpty([])); //Empty array
console.log(isArrayEmpty({})); //Error - arr.join is not a function
console.log(isArrayEmpty('')); //Error - arr.join is not a function 

As you can see above, this method is fool proofed against empty objects and strings because you get an error when this method is used with anything other than an array.

toString() method

You can also use the toString() method, which converts a value to a string. Check if the original value is of type array (use the Array.isArray method), and if the converted value is an empty string. If both the conditions are true, you have an empty array in hand, as shown below:

Array.isArray(arr) && arr.toString() === '' 

JSON.stringify() method

You can also use the JSON.stringify() method. When you convert an empty array into a JSON string, you should get ‘[]’ as the result, and you can check against this string, as shown below:

JSON.stringify(arr) === '[]' 

Higher order array methods

There are also several higher order array methods that can be manipulated to make our check.

Using the Filter method

The ‘filter’ method, as the name implies, iterates though all the elements of a given array, and returns a new array with elements that pass a given condition.

If we make sure the condition is true for all the iterations, you’ll get back the entire array at the end.

console.log([1,2,3].filter(() => true)); // [1,2,3]
console.log([].filter(() => true)); // [] 

Now, you can check if the result of this retuned array is 0. If it is, then your array is empty, and not otherwise, as shown below:

function isEmptyArray(arr) {
  return (arr.filter(() => true).length === 0) ? 'Empty array' : 'Not an empty array, or not an array';
}

console.log(isEmptyArray([1,2,3])); //Not an empty array
console.log(isEmptyArray([])); //Empty array
console.log(isEmptyArray({})); //Error - arr.filter is not a function
console.log(isEmptyArray('')); //Error - arr.filter is not a function 

As you can see above, you don’t have to check if your value is an array because the ‘filter’ method will return a ‘arr.filter is not a function’ error for any value that’s not an array.

Using the Some method

We can manipulate and use the ‘some’ method as well. This method returns true if at least one element passes the given condition. So, we can make sure to return ‘true’ for every iteration, and we’ll get ‘true’ for arrays with elements, and ‘false’ for empty arrays, as shown below:

console.log([1,2,3].some(() => true)); // true
console.log([].some(() => true)); // false 

In practice though, while checking for the condition, ‘not’ the result of the ‘some’ function, and when the string is empty, the ‘if’ condition will be executed. 

!arr.some(() => true) 

This method returns errors for any value other than an array as well.

Using the Every method

The ‘every’ method returns true only if every single element passes the given condition. So, if we check if every element is undefined, empty arrays, which have no value (undefined as of now) will return true and any array with even a single element will return a false value, as shown below:

console.log([1,2,3].every(a => a === undefined)); // false
console.log([].every(a => a === undefined)); // true 

In practice, the below code snippet is how you’ll use the ‘every ‘ method to check if an array is empty:

arr.every(a => a === undefined) 

This method returns an error for anything other than arrays as well.

Using the Find method

The ‘find’ method will return the value of the first element that passes the given test. Make sure the test is true all the time.
Once you do that, if your array is not empty, you should get the first element as the result.

On the other hand, if there are no elements, you’ll get back ‘undefined’. If the result is undefined, you can conclude that your array is empty.

console.log([1,2,3].find(() => true)); // 1 - first element by default
console.log([].find(() => true)); // undefined - no element found - empty string 

This method returns errors for any other data type than arrays as well. So, in your ‘if’ condition, ‘not’ the condition we just created, so the condition returns a ‘true’ when the array is empty, as shown below:

!arr.find(() => true)) 

Using the findIndex method

The findIndex method

The ‘findIndex’ method is used to find the index of the first element that passes the given test.

So, if you return ‘true’ for every iteration, all the elements in the array will pass the test now, so then you’ll get back 0, which refers to the index of the first element of the matching elements.

If you use the same condition on an empty array, you’ll get back -1 because that’s what the ‘findIndex’ method returns when it can’t find even a single matching element.

console.log([1,2,3].findIndex(() => true)); // 0 - first index by default
console.log([].findIndex(() => true)); //-1 

So, to check if our element is empty, create a condition where findIndex always returns true, and check if it’s equal to -1, as shown below:

arr.findIndex(() => true) === -1 

This method won’t work with any other data types, as usual, so it’s also foolproof.

That’s it! We looked at several ways to check if an array is empty in JavaScript, from checking the length and the type of the element, using various pre-defined JavaScript string and JSON methods, to finally, using several higher-order array methods like filter, some, every etc.

Leave a Comment