Sometimes, we want to check if all elements in array are strings with JavaScript.
In this article, we’ll look at how to check if all elements in array are strings with JavaScript.
How to check if all elements in array are strings with JavaScript?
To check if all elements in array are strings with JavaScript, we can use the array every
method and the typeof
operator.
For instance, we write:
const check = arr => arr.every(i => (typeof i === "string"));
console.log(check(['foo', 'bar']))
console.log(check(['foo', 'bar', 1]))
to define the check
function that calls arr.every
with a callback that checks of each entry i
is a string with typeof
.
As a result, the first console log logs true
and the 2nd one logs false
since the first array have all string entries but the 2nd array has one entry that’s not a string.
Conclusion
To check if all elements in array are strings with JavaScript, we can use the array every
method and the typeof
operator.