We gonna use ECMAScript 2016’s new includes()
method to determine whether an array contains a specific element. The new method includes(searchElement, fromIndex) function searches an array for a specific value and returns the corresponding boolean, return true if it exists otherwise false. An optional argument fromIndex allows to search from a specific index.
Let’s see some basic examples:
var a = [1, 2, 3]; a.includes(2); // true a.includes(4); // false
Syntax of includes()
arr.includes(searchElement) arr.includes(searchElement, fromIndex)
Parameters
searchElement – The element to search for.
fromIndex(Optional) – Default value is zero. The position in this array at which to begin searching for searchElement. A negative value searches from the index of array.length + fromIndex by asc.
Let’s see concise examples:
let technologies = ['PHP', 'JS', 'Ruby','NodeJS']; technologies.includes('PHP', 1); // => false technologies.includes('JS', 1); // => true technologies.includes('Ruby', 10); // => false technologies.includes('PHP', -3); // => false technologies.includes('NodeJS', -3); // => true
'PHP'
element has index 0
in technologies. However the search starts from 1
and the index 0
is skipped, so the element is not found.
'JS'
has index 1
, thus the search starts from index 1
, so include()
is able to find it.
The 'Ruby'
element is checked from index 10
, which is bigger than the array length 4
. includes()
method for such situations returns false
.
The index to begin searching parameter is a negative number -3
and the search starts from index 4 - 3 = 1
. The searched 'PHP'
is compared only with 'JS'
, 'Ruby'
and 'NodeJS'
elements, so there is no match.
When searching for 'NodeJS'
element with the same -3
offset, it is a matches.