Check if Array contains Empty String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 16, 2021

banner

Photo from Unsplash

Check if Array contains Empty String #

To check if an array contains an empty string, call the includes() method passing it an empty string - includes(''). The includes method returns true if the provided value is contained in the array and false otherwise.

index.js
const arr = ['a', '', 'c']; const result = arr.includes(''); console.log(result); // 👉️ true

We use the Array.includes method to check if the array contains an empty string.

The parameter we pass to the method is the value to search for in the array.

The includes method returns true if it finds the value in the array and false if it doesn't.

The includes method is not supported in Internet Explorer. If you have to support the browser, use the next approach in this article.

To check if an array contains an empty string:

  1. Call the some() method, passing it a function.
  2. On each iteration, check if the current element is equal to an empty string and return true if the condition is met.
  3. The some method returns true if the provided function returns true at least once.
index.js
// supported in IE const arr = ['a', '', 'c']; const result = arr.some(element => { if (element === '') { return true; } }); console.log(result); // 👉️ true

The function we pass to the Array.some method gets called with each element in the array until it returns true, or iterates over the entire array.

We check if the current element's value is equal to an empty string and return true if it is.

If the function returns true at least once, the some method short-circuits and also returns true.

This is good for performance because we don't have to keep iterating after we've found the answer.

This solution is not as elegant as the includes method, however if you have to support Internet Explorer, it gets the job done.

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.