Check if Array contains Empty Elements in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 16 20212 min read

banner

Photo by Cody Black

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 #

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