Check if an Array contains Undefined in JavaScript

avatar

Borislav Hadzhiev

Sat Nov 13 20212 min read

Check if an Array contains Undefined #

Use the 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.

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 compare the current array element with undefined using the strict equality (===) operator.

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

This approach also works in 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.

For our use case this works just fine.

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