Is there any advantage to Array.prototype.includes() over Array.prototype.indexOf() depending on browsers (Chrome, Firefox) and needle item position (at the begging, middle, ending of the array)?
Array.prototype.includes vs. Array.prototype.indexOf
There is no browser specific information, there is no position in the array specific information, and I don't ask about NaN
value.
indexOf will accept a regular expression but always return -1, which isn't too helpful. So while includes will be a tiny, tiny amount slower because it has to check if you passed it a regex, in reality this will make no difference to how fast your code runs.
indexOf() returns the index if found, -1 if not. If you are searching for NaN (not a number) in an array, use . includes().
indexOf() – also runs in linear time. It iterates through the internal array and checks each element one by one, so the time complexity for this operation always requires O(n) time.
Basically indexOf & lastIndexOf are native javascript functions. Both functions can be applied on Strings as well as Arrays . The indexOf return the very first index where the element matched. On the other hand lastIndexOf returns the last index where the element matched.
I made a test using array with 10 000 numeric values, here is results:
Chrome:
Firefox:
So, indexOf()
in Chrome works much faster than includes()
in all positions.
In Firefox both indexOf()
and includes()
works almost similar.
If you wonder about performances, here is a JSperf test that tend to show that more the time pass, more includes()
will be faster than indexOf
.
JSperf
IMHO, i also prefer to write if (arr.includes(el)) {}
since it is clearer and more maintainable than if (arr.indexOf(el) !== -1) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With