Sub topic 8
Finding Values: indexOf, lastIndexOf, and includes
This chapter assumes you know JavaScript variables and arrow functions, basic array indexing, and how objects and property access work. It covers the three built-in methods that search an array for a specific value: indexOf, lastIndexOf, and includes. All three do a linear search. A linear search checks elements one at a time until it finds a match or runs out of elements, so it takes O(n) time.
The Working Model
Each method takes a value and compares it with the array's elements. They differ in what they return and in how they decide that two values are equal.
| Method | Returns | Direction | Equality rule |
|---|---|---|---|
| `indexOf(value, fromIndex)` | First matching index, or `-1` | Start to end | Strict equality (`===`) |
| `lastIndexOf(value, fromIndex)` | Last matching index, or `-1` | End to start | Strict equality (`===`) |
| `includes(value, fromIndex)` | `true` or `false` | Start to end | SameValueZero |
SameValueZero is the same as === with one difference: it treats NaN as equal to NaN. Under ===, NaN is never equal to anything, including itself. Both rules treat +0 and -0 as equal.
const values = [1, NaN, 3, 1];
console.log(values.indexOf(NaN)); // -1
console.log(values.includes(NaN)); // true
console.log(values.lastIndexOf(1)); // 3indexOf cannot find NaN at all. If your data can contain NaN, use includes to check for it, or findIndex(Number.isNaN) to get its position.
Starting From a Different Position
All three methods take an optional second argument, fromIndex. For indexOf and includes, it sets where the forward search starts. For lastIndexOf, it sets where the backward search starts. A negative fromIndex counts from the end of the array, so -2 means length - 2.
const letters = ['a', 'b', 'a', 'c', 'a'];
console.log(letters.indexOf('a')); // 0
console.log(letters.indexOf('a', 1)); // 2
console.log(letters.indexOf('a', -2)); // 4 (starts at index 3)
console.log(letters.lastIndexOf('a')); // 4
console.log(letters.lastIndexOf('a', 3)); // 2 (searches back from index 3)
console.log(letters.lastIndexOf('a', -3)); // 2 (searches back from index 2)
console.log(letters.includes('b', 2)); // falseYou can use fromIndex to collect every position of a value by restarting the search one step past the last hit:
function allIndexes(arr, value) {
const result = [];
let i = arr.indexOf(value);
while (i !== -1) {
result.push(i);
i = arr.indexOf(value, i + 1);
}
return result;
}
console.log(allIndexes(['a', 'b', 'a', 'c', 'a'], 'a')); // [0, 2, 4]Choosing a Method
Predicate methods are covered in the next chapter. Use them whenever matching depends on a condition and not on one exact value.
Common Errors
Treating the index as a boolean
indexOf returns 0 when the match is the first element, and 0 is falsy. This check fails for exactly that case:
const roles = ['admin', 'editor'];
if (roles.indexOf('admin')) {
console.log('found'); // never runs: indexOf returned 0
}
if (roles.indexOf('admin') !== -1) {
console.log('found'); // runs
}
if (roles.includes('admin')) {
console.log('found'); // runs, and states the intent clearly
}If you don't need the position, use includes.
Searching for objects by content
Strict equality compares objects by reference, not by their properties. Two objects with identical properties are still different values.
const user = { id: 1 };
const users = [user];
console.log(users.includes({ id: 1 })); // false: a different object
console.log(users.includes(user)); // true: the same reference
console.log(users.findIndex(u => u.id === 1)); // 0To match objects by their contents, use a predicate method such as findIndex or some.
Expecting type coercion
Neither rule converts types, so '2' and 2 do not match:
console.log([1, 2, 3].includes('2')); // false
console.log([1, 2, 3].indexOf(2)); // 1Values that arrive as strings, such as form input or URL parameters, need converting with Number() before you search a numeric array.
Cost
Each call scans the array, so it takes O(n) time in the worst case. A single lookup on a few hundred elements costs very little. If you call includes inside a loop over another large array, the total work grows to O(n × m). A later chapter shows how a Set handles that pattern.
Exercise
Given const data = [0, -0, NaN, 5, 0]; what do data.indexOf(-0), data.lastIndexOf(0), data.indexOf(NaN), data.includes(NaN), and data.indexOf(0, -2) return?
Show answer
data.indexOf(-0) is 0, because +0 and -0 are equal under ===. data.lastIndexOf(0) is 4. data.indexOf(NaN) is -1, because NaN is never === to itself. data.includes(NaN) is true, because SameValueZero treats NaN as equal to NaN. data.indexOf(0, -2) starts searching at index 3 and finds 0 at index 4, so it returns 4.
Exercise
A teammate writes if (!tags.indexOf('urgent')) { skip(); } to skip items that lack the 'urgent' tag. What goes wrong, and how should it be written?
Show answer
indexOf returns -1 when the tag is missing, and -1 is truthy, so !(-1) is false and missing tags are never skipped. When 'urgent' is at index 0, !0 is true, so items with the tag in first place are skipped by mistake. Write if (!tags.includes('urgent')) { skip(); } instead.