Categories
JavaScript Answers

How to check if all elements in array are strings with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *