Check if an element is present in an array
Concisely check if an element is in an array using the Array.includes()
method. It provides a direct boolean
return—true
if the element is found, otherwise false
.
Effortlessly streamline your code with Array.includes()
.
Peek under the hood
Array.includes()
basics
Introduced in ECMAScript 2016, Array.includes()
is your go-to method for element presence checks. It's efficient and, most importantly, super readable.
Specifying index
Cleverly, Array.includes()
takes an optional second parameter for the start index. Say goodbye to unnecessary full-array searches!
Unique objects
Remember, in JavaScript, all objects are unique snowflakes—even if they look identical. Consequently, Array.includes()
treats similar objects as different.
Browser compatibility
While Array.includes()
is widely supported, some older browsers might not recognize it. Use a polyfill for those Internet Explorer die-hards.
indexOf
as a substitute
In the land before Array.includes()
, there was Array.indexOf()
. Now, it gathers dust in many cases but it's a good fallback.
Translating indexOf results to boolean
Seeing true
or false
is a clear signal. Use double negation (!!
) or add 1 to transform indexOf
's result to a boolean:
Original order is maintained
The best part about Array.includes()
and indexOf()
? No need to sort your array. Stay original, folks!
Performance measures
It's always good to benchmark. Test methods like includes
and indexOf
to pick the fittest one for your case.
Practical cases
Speed up search with start index
What if you're certain that your desired element won't appear in the first part of the array? Don't waste time—cut to where matter starts:
Implement a polyfill
To make ancient browsers understand Array.includes()
, you can implement a homemade polyfill:
Performance and Array.includes()
Though readability is usually crucial, it's important to remember that Array.includes()
performs differently in various JS engines due to optimization strategies. indexOf
performs a linear search, on average making n/2 comparisons. Always think of your specific use case.
Was this article helpful?