some takes in a callback function where you can write your own logic to determine if an array contains some element which matches the conditions you wrote.
includes does a generic equalTo comparison on every element and will return true if at least one element in the array is equal to the value to find.
Videos
I understand how each of these methods work, but they all seem to have similar functions to one another, and I'm not sure as to what situation might call for what method.
tl;dr: NaN is treated differently:
[NaN].indexOf(NaN) > -1isfalse[NaN].includes(NaN)istrue
From the proposal:
Motivation
When using ECMAScript arrays, it is commonly desired to determine if the array includes an element. The prevailing pattern for this is
if (arr.indexOf(el) !== -1) { ... }with various other possibilities, e.g.
arr.indexOf(el) >= 0, or even~arr.indexOf(el).These patterns exhibit two problems:
- They fail to "say what you mean": instead of asking about whether the array includes an element, you ask what the index of the first occurrence of that element in the array is, and then compare it or bit-twiddle it, to determine the answer to your actual question.
- They fail for
NaN, asindexOfuses Strict Equality Comparison and thus[NaN].indexOf(NaN) === -1.Proposed Solution
We propose the addition of an
Array.prototype.includesmethod, such that the above patterns can be rewritten asif (arr.includes(el)) { ... }This has almost the same semantics as the above, except that it uses the SameValueZero comparison algorithm instead of Strict Equality Comparison, thus making
[NaN].includes(NaN)true.Thus, this proposal solves both problems seen in existing code.
We additionally add a
fromIndexparameter, similar toArray.prototype.indexOfandString.prototype.includes, for consistency.
Further information:
SameValueZeroalgorithmStrict Equality Comparisonalgorithm
Technically
NaNorundefinedwill not be findable when usingindexOf.
[NaN].indexOf(NaN) // => -1 (not found)
[NaN].includes(NaN) // => true
[undefined].indexOf(undefined) // => -1 (not found)
[undefined].includes(undefined) // => true
includesalso is of no use if you want to know at where index the element was found.While searching a string,
includesaccepts regexpes as opposed to indexOf
Readability
arr.includes('searchedElement')does what it says and it is obvious that it returns aboolean.- while
arr.indexOf('searchedElement') !== -1to know if something exists in a string or an array is less more readable.
Performances
According to this article on the subject there are no noticeable difference although includes may be a very little bit slower.
History
indexOf was created way before includes.
Browser support
indexOf=> 97.08%includes=> 97.51%
So both can be used safely.