How to check if a JavaScript array contains a specific value

By

Learn how to check if a JavaScript array contains a specific value using the includes() method, which returns true or false depending on whether it is found.

~~~

To check if a JavaScript array contains a specific value, use the includes() method on the array instance. It returns true if the value is found, false otherwise.

For example:

['red', 'green'].includes('red') //true ✅

['red', 'green'].includes('yellow') //false ❌

Since it returns a boolean, it slots directly into an if:

const colors = ['red', 'green']

if (colors.includes('red')) {
  //do something
}

Note that string comparison is case sensitive. 'Red' and 'red' are different values:

['red', 'green'].includes('Red') //false

It works with any primitive value, of course, not just strings:

[10, 25, 50].includes(25) //true

One thing not to confuse: strings have their own includes() method too, which checks for a substring. Same name, different job. Here we’re talking about the array one.

Searching from a specific position

includes() accepts a second argument, the index where the search starts:

const colors = ['red', 'green', 'blue']

colors.includes('red', 1) //false
colors.includes('blue', 1) //true

The first check is false because starting from index 1, 'red' is behind us. You’ll rarely need this, but it’s there.

How did we do this before?

includes() arrived with ES2016. Before that, the common pattern was indexOf():

['red', 'green'].indexOf('red') !== -1 //true

It works, but reads worse. There’s also a subtle difference: indexOf() can’t find NaN, while includes() can:

[NaN].indexOf(NaN) //-1
[NaN].includes(NaN) //true

Unless you need to support very old browsers, use includes().

Watch out with objects

includes() compares objects by reference, not by content. Two objects that look identical are still different objects:

const people = [{ name: 'Anna' }]

people.includes({ name: 'Anna' }) //false

The object we pass in is a brand new one, so it’s not the same object stored in the array, even if the properties match.

To check by content, use some() with a condition:

people.some((person) => person.name === 'Anna') //true

some() returns true as soon as one element passes the test. That makes it the right tool whenever “contains” means “an item matching this condition”, rather than “this exact value”.

The same idea scales to multiple values. To check if an array contains at least one of several candidates, combine some() with includes():

const colors = ['red', 'green', 'blue']
const candidates = ['red', 'yellow']

candidates.some((c) => colors.includes(c)) //true

Swap some() for every() to check that all the candidates are in the array.

~~~

Related posts about js: