Check if Array contains Empty Elements in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 16, 2021

banner

Photo from Unsplash

Check if Array contains Empty Elements #

To check if an array contains empty elements call the includes() method on the array, passing it undefined as a parameter. The includes method will return true if the array contains an empty element or an element that has the value of undefined.

index.js
const arr = [1, , 3]; console.log(arr[1]); // 👉️ undefined console.log(arr.includes(undefined)); // 👉️ true if (arr.includes(undefined)) { console.log(`✅ array contains an empty element(s) or undefined value(s)`); } else { console.log(`⛔️ array DOESN'T contain an empty element or undefined value`); }

We have an empty element in the array at index 1. If we try to access the element, we get a value of undefined back.

We use the Array.includes method to check if the array includes a value of undefined.

Note that this check would also pass if the array contains an element with a value of undefined, e.g.:

index.js
const arr = [1, undefined , 3]; console.log(arr.includes(undefined)); // 👉️ true

If you need to make sure the array contains an empty element and not undefined values, use this approach instead.

index.js
const arr = [1, , 3]; console.log(arr.indexOf(undefined)); // 👉️ -1 if (arr.indexOf(undefined) === -1 && arr.includes(undefined)) { console.log('✅ array contains empty element(s)'); } else { console.log("⛔️ array DOESN'T contain empty elements"); }

We use the logical and (&&) operator to chain multiple conditions.

In our if statement, we check if the Array.indexOf method returns -1 and the array includes undefined.

This check would only succeed if the array has one or more empty elements.

The indexOf method returns -1 only when it doesn't find the provided value in the array.

The includes() method treats the empty array elements as undefined, however the empty element does not actually have the value of undefined.

This is why the indexOf method doesn't find an element with the value of undefined in the array.

If both of the conditions in our if statement are satisfied, we can be sure that the array contains one or more empty elements.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.