Explain Codes LogoExplain Codes Logo

How do I check if an array includes a value in JavaScript?

javascript
includes
performance
polyfills
Alex KataevbyAlex Kataev·Aug 11, 2024
TLDR

To quickly check for a value in an array, use the includes() method:

const array = [1, 2, 3]; // Here we go! console.log(array.includes(2)); // true, number 2 does have friends!

This ES2016 method finds a specific element, even efficiently spotting NaN values, which other methods could miss (looking at you, indexOf()).

Handling older browsers

If you're dealing with older browsers, they may lack support for includes(). In this case, indexOf() is your loyal fallback companion:

const array = [1, 2, 3]; console.log(array.indexOf(2) !== -1); // true, Internet Explorer is not dying today!

For universal compatibility, polyfills like those from core-js can provide includes() functionality across all browsers.

Complex conditions at play

For those moments when simple equality is not enough, Array.prototype.some() lends its power:

const array = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }]; const hasNameBob = array.some(person => person.name === 'Bob'); // true, Bob's not an imaginary friend!

This method stops searching upon finding a match, saving you precious milliseconds.

Performance optimization

In situations where performance is your ultimate focus, a reverse while loop often outperforms .includes() or .some():

const array = [1, 2, 3]; let containsTwo = false; let i = array.length; while (i--) { if (array[i] === 2) { containsTwo = true; break; } } // True, who said while loops were old-fashioned?

In performance-critical scenarios, benchmarking different methods for your JavaScript engine can reveal the quickest.

Frameworks and ecosystems

Different frameworks or libraries may provide similar functionality with their twists:

  • jQuery: $.inArray(value, array) > -1 can replace array.includes(value).
  • Lodash: use _.includes(array, value) for more utility features.
  • Ramda.js: R.includes(value, array) is made for functional programming addicts.

Be cautious with prototype extensions

You can extend array prototypes to add .includes() to older environments. However, such actions can come with side effects.

if (!Array.prototype.includes) { Array.prototype.includes = function(searchElement /*, fromIndex*/ ) { // implementation of includes }; }

Instead of directly tampering with prototypes, consider safer alternatives like polyfills or helper functions.