lukedavies.dev

Search by title or category tag

How to check an array of strings includes a string

Luke Davies

jsjs-cheatsheet

22/03/2023

There’s a couple ways to do this.

We can use indexOf() or the more modern approach of includes()

indexOf() will return 0 if the string exists in the array and -1 if it doesnt

includes() will return true or false


Here’s a code example:

const arr = ['A', 'B', 'C'];
console.log(arr.includes('A')) // true
console.log(arr.includes('D')) // false

console.log(arr.indexOf('A')) // 0
console.log(arr.indexOf('D')) // -1 


indexOf() was the standard approach but since ECMA2016+ we’ve been able to use includes()

Note: IE does not support includes() but since Edge that shouldnt be a huge issue. Compatability table here

lukedavies.dev 2023