Check if an Array contains Undefined in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if an Array contains Undefined #

Use the Array.includes() method to check if an array contains undefined values, e.g. arr.includes(undefined). The includes method will return true if the array contains at least one undefined value and false otherwise.

index.js
function containsUndefined(arr) { return arr.includes(undefined); } console.log(containsUndefined([1, undefined])); // 👉️ true console.log(containsUndefined([1, 2])); // 👉️ false

We created a reusable function that checks if the supplied array contains at least one undefined value.

The Array.includes method takes a value and checks for its existence in the array.

index.js
// 👇️ true console.log([1, undefined, 3].includes(undefined)); // 👇️ false console.log([1, 2, 3].includes(undefined));
If the value is contained in the array, the method returns true, otherwise it returns false.

Note that this approach would also work if there is an empty element in the array:

index.js
function containsUndefined(arr) { return arr.includes(undefined); } console.log(containsUndefined([, 2])); // 👉️ true console.log(containsUndefined([])); // 👉️ false

We skipped the first element in the array using a comma, however it still counts as an undefined value.

An alternative approach is to use the Array.some method.

To check if an array contains undefined values, use the some() method to iterate over the array. On each iteration, compare the array element to undefined and return the result. If the array contains at least one undefined value, the some method will return true.

index.js
function containsUndefined(arr) { return arr.some(element => element === undefined); } console.log(containsUndefined([1, undefined])); // 👉️ true console.log(containsUndefined([1, 2])); // 👉️ false
The function we passed to the some method gets called with each element in the array, until it returns a truthy value or iterates over the entire array.

If the function returns a truthy value at least once, the some method short-circuits, returning true.

On each iteration, we check if the current array element is equal to undefined using the strict equality (===) operator.

If the condition is met at least once, the some method will return true.

This approach also works if the array contains empty elements.

index.js
function containsUndefined(arr) { return arr.some(element => element === undefined); } console.log(containsUndefined([, undefined])); // 👉️ true console.log(containsUndefined([])); // 👉️ false
Note that calling the some method on an empty array returns false for any condition.

This works just fine for our use case.

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.