5 ways to check if Javascript Array is empty

plus Typescript tip

I'll shortly describe what Javascript (JS) array is, how we basically use it and then I'll describe how we can check whether it's empty. There are more ways to do it so I'll describe them gradually since JS language is evolving and now we have better and more concise ways to do it. If you work with Typescript (TS), there's an interesting and more bullet proof way to check for empty arrays too.

Intro to JS arrays

JS arrays serve for storing the multiple values in a list. JS array is a sub-type of JS object. That means it extends the behaviour of JS object in some way. The literal syntax of the array uses square brackets:

let myArray = []

while the object uses curly brackets:

let myObject = {}

JS arrays use numerical indexes, starting with the index 0. They have also length property, which is self-explanatory. Here's an example:

let myArray = [1, 245, 'apple', { type: 'fruit' }]

myArray.length
// 4

The length of this array is 4 and you can see we can mix any values we want (numbers, strings, objects, etc.) This is how we can access individual values:

myArray[0]
// 1

myArray[2]
// 'apple'

Caveat

There are so called 'empty slots' in JS arrays.

If you assign an index of an array more than one position beyond the current end of the array, JS will leave the in between slots "empty" rather than auto-assigning them to undefined as you might expect.

Given the array we defined above we could do the following:

myArray[10] = 'carrot'
myArray.length
// 11

All other positions would be undefined.

There are many methods on arrays and we can do much more, but as an introduction this will do. The main part of the article follows:

Is JS array empty? Does it exist?

Let's describe 5 ways for checking if JS array is empty and whether it exists.

1. The length property

The first thing you might think of is the length property, which we already covered.

myArray.length ? true : false

This would return false if the length is 0. What if myArray is undefined for example? Or what if we get null instead, because a value comes from backend? We need to make sure that myArray exists, otherwise we would get the following error:

image.png

2. And (&&) operator and length

We can use && operator to avoid previous error.

myArray && myArray.length ? true : false

This is fine, but there's a shorter way using the optional chaining operator .?.

3. Optional chaining (.?)

Instead of using && operator to check if myArray exists and at the same time has the length property, we can write:

myArray?.length ? true : false

Speaking about the operators, I'd like to mention also the Nullish coalescing operator (??). Our array contains also an object, so we could check its property.

let myArray = [1, 245, 'apple', { type: 'fruit' }]
myArray?.[3]?.type ?? 'No type property'
// 'fruit'

We get whatever we evaluate on the left side if it's true, otherwise we get what is on the right side of ??.

4. Logical NOT (!)

It depends on what you really need, but here's another way. Logical not operator negates the values. The following would return true in case myArray is empty, that is [], or undefined or null.

!myArray?.length ? true : false

5. isArray() method

How do we really know if we work with the array though? The length property exists also on the string. We could use isArray() method:

let myArray = [1, 245, 'apple', { type: 'fruit' }]
Array.isArray(myArray)
// true

Obviously you can combine the approaches listed above. For example:

if (Array.isArray(myArray) && myArray.length) {
  // array exists and is not empty
}

Typescript solution

I recommend reading this article from Luca Del Puppo to see how the snippet below works in detail.

export interface NonEmptyArray<A> extends ReadonlyArray<A> {
  // tslint:disable-next-line: readonly-keyword
  0: A;
}
type ReadOnlyNotEmptyArray<T> = Readonly<NotEmptyArray<T>>;

function isNotEmptyArray<T>(as: T[]): as is NotEmptyArray<T> {
  return as.length > 0;
}

Conclusion

I listed several ways we can utilize the operators to work with the arrays and check whether they are empty or not. We started with the length property and introduced operators like &&, optional chaining .?, Nullish coalescing operator ?? and finally isArray() method. If you work with TypeScript, you could incorporate to your application also the snippet that checks for empty array.

Depending on your needs, you can choose one or more approaches and combine them together, or you could also write helper functions like the one for Typescript. I hope you find this article useful.

References