Borislav Hadzhiev
Sat Oct 16 2021·2 min read
Photo by Greg Kantra
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.
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.
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:
some()
method, passing it a function.true
if the condition is met.some
method returns true
if the provided function returns true
at
least once.// 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.