Check if a String is contained in an Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if a String is contained in an Array #

To check if a string is contained in an array, call the includes() method, passing it the string as a parameter. The includes method will return true if the string is contained in the array and false otherwise.

index.js
const arr = ['one', 'two', 'three']; if (arr.includes('two')) { console.log('✅ String is contained in Array'); } else { console.log('⛔️ String is NOT contained in Array'); }

We used the Array.includes method to check if the string two is contained in the array.

The includes method returns true if the provided value is found in the array and false otherwise.

Note that the includes method performs a case-sensitive comparison.

If you need to perform a case-insensitive check whether a string is contained in an array, use the Array.some method.

index.js
const arr = ['one', 'two', 'three']; const two = 'TWO'; const containsString = arr.some(element => { return element.toLowerCase() === two.toLowerCase(); }); console.log(containsString); // 👉️ true
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.

We used the toLowerCase() method to lowercase the array element and the string to perform a case-insensitive comparison.

If the function we passed to the some() method returns a truthy value at least once, the method short-circuits and returns true.

You can also use the indexOf method as an alternative to includes().

Check if a String is contained in an Array using indexOf #

To check if a string is contained in an array, call the indexOf method, passing it the string as a parameter. The indexOf method returns the index of the first occurrence of the string in the array, or -1 if the string is not contained in the array.

index.js
const arr = ['one', 'two', 'three']; if (arr.indexOf('two') !== -1) { console.log('✅ String is contained in Array'); } else { console.log('⛔️ String is NOT contained in Array'); }

We used the Array.indexOf method to check if the string two is contained in the array.

If the string is not contained in the array, the indexOf method returns -1, otherwise it returns the index of the first occurrence of the string in the array.

Which approach you pick is a matter of personal preference. I'd go with using the includes() method as I find it more readable and direct.

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.