How do I check if an array includes a value in JavaScript?
To quickly check for a value in an array, use the includes()
method:
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:
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:
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()
:
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 replacearray.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.
Instead of directly tampering with prototypes, consider safer alternatives like polyfills or helper functions.
Was this article helpful?