Array .includes() / indexOf() / lastIndexOf() Since: ES2016(ECMAScript 2016)
Methods for checking whether an array contains a specific value or finding the position of a value. includes() returns a boolean, while indexOf() returns an index.
Syntax
// Check whether a value is contained in the array. var result = array.includes(searchValue, startIndex); // Return the index of the first occurrence of a value. var index = array.indexOf(searchValue, startIndex); // Return the index of the last occurrence of a value. var index = array.lastIndexOf(searchValue, startIndex);
Methods
| Method | Description |
|---|---|
| includes(value, startIndex) | Returns true if the array contains the specified value, or false if it does not. The start index is optional. |
| indexOf(value, startIndex) | Returns the index of the first occurrence of the specified value. Returns -1 if not found. |
| lastIndexOf(value, startIndex) | Returns the index of the last occurrence of the specified value. Returns -1 if not found. |
Sample Code
var colors = ["red", "blue", "green", "blue", "yellow"];
// Check whether a value is contained in the array.
console.log(colors.includes("blue")); // Outputs: true
console.log(colors.includes("purple")); // Outputs: false
// Return the index of the first occurrence.
console.log(colors.indexOf("blue")); // Outputs: 1
console.log(colors.indexOf("purple")); // Outputs: -1 (not found)
// Return the index of the last occurrence.
console.log(colors.lastIndexOf("blue")); // Outputs: 3
// Search starting from a given index.
console.log(colors.indexOf("blue", 2)); // Outputs: 3 (searches from index 2 onward)
// NaN handling differs between the two methods.
var arr = [1, NaN, 3];
console.log(arr.includes(NaN)); // Outputs: true
console.log(arr.indexOf(NaN)); // Outputs: -1 (indexOf cannot detect NaN)
Notes
array.includes() is the best choice when you only need to know whether a value exists. Because it returns a boolean directly, you can use it as an if condition without the verbose array.indexOf() !== -1 pattern. It was added in ES2016 and has the added benefit of correctly handling NaN.
array.indexOf() has been available since ES5 and is useful when you need to know the position of a value. Because NaN === NaN evaluates to false in JavaScript, array.indexOf() cannot detect NaN. Use array.includes() to check for the presence of NaN.
These methods use strict comparison (equivalent to ===), so values of different types will not match. Objects and arrays match only if they share the same reference. For advanced searches using a condition function, use array.find() / array.findIndex().
Browser Compatibility
46 or earlier ×
42 or earlier ×
Android Browser
52+ ○
46 or earlier ×
Chrome Android
52+ ○
46 or earlier ×
Firefox Android
79+ ○
42 or earlier ×If you find any errors or copyright issues, please contact us.