Available in Chrome 47+ | View on GitHub | Browse Samples
To determine if an array includes an element, we could use the popular if
(arr.indexOf(el) !== -1)
pattern which exhibits two problems: It fails to
"say what you mean", and also fails for NaN
, as indexOf
uses Strict Equality
Comparison and thus [NaN].indexOf(NaN) === -1
.
The new Array.prototype.includes
method is an ECMAScript 2016 (ES7) proposal. It can be used to determine
whether an array includes a given element in an elegant way.
It compares first arguments to the elements of the array, in ascending order,
using the SameValueZero algorithm
and if found at any position, returns true
; otherwise,
false
is returned.
The optional second argument fromIndex
defaults to
0
(i.e. the whole array is searched). If it is negative, it is
used as the offset from the end of the array to compute
fromIndex
.