Sub topic 8
Finding Values: indexOf, lastIndexOf, and includes
The earlier chapters put arrays in order. This one starts the searching half of the tutorial with the simplest question you can ask an array: "Is this value in here, and if so, where?" JavaScript answers it with three built-in methods: indexOf, lastIndexOf, and includes. They look alike, but they differ in what they return, how they compare values, and how they handle edge cases. Those differences cause real bugs.
This chapter assumes you know JavaScript variables, functions, and arrow functions, along with basic array indexing, objects, and the difference between mutating an array and creating a new one. It doesn't need the sorting chapters, but it helps to remember from them that arrays can hold mixed types and missing slots.
The Three Methods at a Glance
All three methods do a linear search. A linear search checks elements one at a time, in order, until it finds a match or runs out of elements. You give each method a value, not a condition. If you need to search by a condition such as "the first order over $50", you want find and its relatives from the next chapter.
| Method | Returns | Direction | Equality used | Finds `NaN` |
|---|---|---|---|---|
| `indexOf(value, fromIndex)` | First matching index, or `-1` | Start to end | Strict equality (`===`) | No |
| `lastIndexOf(value, fromIndex)` | Last matching index, or `-1` | End to start | Strict equality (`===`) | No |
| `includes(value, fromIndex)` | `true` or `false` | Start to end | SameValueZero | Yes |
Here is the basic behavior:
const values = [1, NaN, 3, 1];
console.log(values.indexOf(NaN)); // -1
console.log(values.includes(NaN)); // true
console.log(values.lastIndexOf(1)); // 3
console.log(values.indexOf(1)); // 0
console.log(values.indexOf(42)); // -1
console.log(values.includes(42)); // falseUse indexOf and lastIndexOf when you need the position. Use includes when you only need a yes or no answer. Because includes returns a boolean, the intent reads clearly at the call site, and you avoid a whole class of -1 bugs.
How Each Method Compares Values
The comparison rule decides what counts as a match.
Strict equality in indexOf and lastIndexOf
indexOf and lastIndexOf compare with ===. That means:
- No type conversion happens. The string
'2'doesn't match the number2. - Objects, arrays, and functions match only when they are the same reference. Two objects with identical contents are still different objects.
NaN === NaNisfalse, so neither method can ever findNaN.0 === -0istrue, so positive and negative zero match each other.
SameValueZero in includes
includes uses an algorithm the specification calls SameValueZero. It works like === with one exception: NaN equals NaN. Like ===, it treats 0 and -0 as equal. (This differs from Object.is, which treats NaN as equal to itself but 0 and -0 as different.)
const nums = [0, NaN, 2];
console.log(nums.includes('2')); // false, no type conversion
console.log(nums.indexOf(-0)); // 0, because -0 === 0
console.log(nums.includes(-0)); // true
console.log(nums.includes(NaN)); // true
console.log(nums.indexOf(NaN)); // -1
console.log(Object.is(0, -0)); // false, a different ruleObjects match by reference
This is the most common surprise for developers coming from languages with value-based equality:
const alice = { id: 1, name: 'Alice' };
const users = [alice, { id: 2, name: 'Bob' }];
console.log(users.indexOf(alice)); // 0
console.log(users.indexOf({ id: 1, name: 'Alice' })); // -1
console.log(users.includes({ id: 2, name: 'Bob' })); // falseThe object literal { id: 2, name: 'Bob' } creates a new object, and that object isn't in the array. To find an object by its contents, such as its id, search by condition with findIndex or some, which the next chapter covers.
The diagram below shows the decision each method makes for every element it visits.
Controlling Where the Search Starts: fromIndex
All three methods take an optional second argument, fromIndex, which sets where the search begins. The rules differ between the forward methods and lastIndexOf.
For indexOf and includes:
- A non-negative
fromIndexstarts the search at that index. - A negative
fromIndexcounts back from the end: the start islength + fromIndex. - If that sum is still negative, the whole array is searched.
- If
fromIndexis greater than or equal tolength, nothing is searched and the result is-1orfalse.
For lastIndexOf:
- The search moves backward from
fromIndex. The default islength - 1. - A negative
fromIndexalso counts from the end. - If
length + fromIndexis negative, nothing is searched and the result is-1.
const letters = ['a', 'b', 'c', 'a', 'b', 'c'];
console.log(letters.indexOf('a', 1)); // 3
console.log(letters.indexOf('c', -2)); // 5, starts at index 4
console.log(letters.indexOf('a', -100)); // 0, clamps to the start
console.log(letters.indexOf('a', 6)); // -1, starts past the end
console.log(letters.lastIndexOf('b')); // 4
console.log(letters.lastIndexOf('b', 3)); // 1, searches indexes 3, 2, 1, 0
console.log(letters.lastIndexOf('b', -3)); // 1, starts at index 3
console.log(letters.lastIndexOf('a', -7)); // -1, nothing searched
console.log(letters.includes('c', 3)); // true
console.log(letters.includes('a', 4)); // falseNon-integer values are truncated toward zero, so fromIndex of 1.9 behaves like 1.
Common Errors
Treating the index as a boolean
indexOf returns 0 when the match is the first element, and 0 is falsy. It returns -1 when there is no match, and -1 is truthy. So a plain if gets both cases wrong.
const roles = ['admin', 'editor'];
if (roles.indexOf('admin')) {
console.log('admin found'); // never runs: indexOf returned 0
}
if (roles.indexOf('guest')) {
console.log('guest found'); // runs: -1 is truthy
}
// Correct options
console.log(roles.indexOf('admin') !== -1); // true
console.log(roles.includes('admin')); // trueOlder code sometimes uses ~roles.indexOf(x). The bitwise NOT turns -1 into 0 and every other index into a non-zero number. It works, but includes says the same thing plainly and also handles NaN.
Splicing with an unchecked index
A common way to remove one occurrence of a value is splice(indexOf(value), 1). If the value is missing, indexOf returns -1, and splice(-1, 1) removes the last element.
function removeBuggy(arr, value) {
arr.splice(arr.indexOf(value), 1);
return arr;
}
function removeSafe(arr, value) {
const i = arr.indexOf(value);
if (i !== -1) arr.splice(i, 1);
return arr;
}
console.log(removeBuggy(['x', 'y', 'z'], 'q')); // ['x', 'y'], 'z' was lost
console.log(removeSafe(['x', 'y', 'z'], 'q')); // ['x', 'y', 'z']
console.log(removeSafe(['x', 'y', 'z'], 'y')); // ['x', 'z']Both versions mutate the array they receive. If you need the original untouched, use arr.filter(v => v !== value) instead. It returns a new array and removes every occurrence, not just the first.
Confusing array search with string search
Strings have their own indexOf and includes, and those search for substrings. Array methods compare whole elements.
console.log('apple pie'.includes('app')); // true, substring
console.log(['apple', 'pie'].includes('app')); // false, no element equals 'app'
console.log(['apple', 'pie'].some(s => s.includes('app'))); // trueExpecting type coercion
Values read from form fields, URLs, and localStorage arrive as strings. Searching a number array with them silently fails.
const ids = [101, 102, 103];
const fromQuery = '102';
console.log(ids.includes(fromQuery)); // false
console.log(ids.includes(Number(fromQuery))); // trueConvert the input once, where it enters your code, rather than at every search.
Edge Cases Worth Knowing
Sparse arrays and undefined
A sparse array has holes, which are indexes with no element at all. A hole is different from an element that holds undefined. indexOf and lastIndexOf skip holes. includes reads each hole as undefined.
const sparse = [1, , 3]; // index 1 is a hole
const dense = [1, undefined, 3];
console.log(sparse.indexOf(undefined)); // -1
console.log(sparse.includes(undefined)); // true
console.log(dense.indexOf(undefined)); // 1
console.log(dense.includes(undefined)); // trueHoles are rare in modern code, but they show up with new Array(n) and with delete arr[i].
Array-like objects
All three methods are generic. They work on any object with a length property and numeric keys, such as arguments, a DOM NodeList, or even a string. You borrow them through Array.prototype with call:
const arrayLike = { length: 3, 0: 'red', 1: 'green', 2: 'blue' };
console.log(Array.prototype.indexOf.call(arrayLike, 'green')); // 1
console.log(Array.prototype.includes.call(arrayLike, 'pink')); // false
console.log(Array.prototype.indexOf.call('hello', 'l')); // 2, per characterWith an array-like you will use often, Array.from(arrayLike) is usually clearer than borrowing methods with call.
Typed arrays
Typed arrays such as Int32Array and Float64Array have their own indexOf, lastIndexOf, and includes with the same semantics. Precision is the gotcha. A Float32Array stores each number as a 32-bit float, so a decimal like 1.1 is rounded on the way in and no longer equals the 64-bit 1.1 you search with.
const f32 = new Float32Array([1.1, 1.5]);
console.log(f32.includes(1.1)); // false, stored value is 1.100000023841858
console.log(f32.includes(Math.fround(1.1))); // true
console.log(f32.includes(1.5)); // true, 1.5 is exact in 32 bits
console.log(new Float64Array([NaN]).includes(NaN)); // trueFinding Every Occurrence
None of the three methods returns all positions, but fromIndex lets you resume after each match:
function allIndexesOf(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(allIndexesOf(['a', 'b', 'a', 'c', 'a'], 'a')); // [0, 2, 4]
console.log(allIndexesOf([1, 2, 3], 9)); // []The loop ends because indexOf returns -1 once i + 1 reaches the length. Each call picks up where the previous one stopped, so the whole function makes a single pass over the array.
Cost and When It Matters
Each call to these methods is O(n). In the worst case, when the value is missing or sits at the end, the method checks every element. For one lookup in a few hundred elements, that cost is negligible. It adds up when you search inside a loop, for example checking each of 10,000 incoming IDs against a 10,000-element array, which can take up to 100 million comparisons. The last two chapters cover the faster options: binary search on sorted data and Set or Map lookups.
Exercises
Exercise
What does each line log, and why? const a = [0, NaN, '5', { k: 1 }]; console.log(a.indexOf(NaN), a.includes(NaN), a.indexOf(5), a.includes(-0), a.indexOf({ k: 1 }));
Show answer
It logs -1 true -1 true -1. indexOf uses ===, and NaN never equals itself, so it returns -1. includes uses SameValueZero, which treats NaN as equal to NaN. The number 5 doesn't strictly equal the string '5'. -0 equals 0 under SameValueZero. The object literal is a new reference, so indexOf can't find it.
Exercise
A teammate writes function hasTag(tags, tag) { return tags.indexOf(tag) ? true : false; }. Give an input where it returns the wrong answer, and fix it.
Show answer
hasTag(['urgent'], 'urgent') returns false because indexOf returns 0, which is falsy. hasTag(['urgent'], 'low') returns true because -1 is truthy. The fix is return tags.includes(tag); or return tags.indexOf(tag) !== -1;.
Exercise
Given const xs = [5, 3, 5, 7, 5], what do xs.indexOf(5, -2), xs.lastIndexOf(5, -2), xs.lastIndexOf(5, undefined), and xs.includes(3, 2) return?
Show answer
They return 4, 2, 0, and false. With a length of 5, -2 becomes index 3. indexOf searches forward from 3 and finds 5 at index 4. lastIndexOf searches backward from 3 and finds 5 at index 2. Passing undefined converts fromIndex to 0, so lastIndexOf checks only index 0, which holds 5. includes starts at index 2, and 3 sits only at index 1, so it returns false.
Exercise
Write a function removeAll(arr, value) that returns a new array with every occurrence of value removed, leaves arr unchanged, and also removes NaN when value is NaN.
Show answer
const removeAll = (arr, value) => arr.filter(v => !(v === value || (Number.isNaN(v) && Number.isNaN(value))));. filter returns a new array, so arr isn't mutated. The extra Number.isNaN check gives NaN the same treatment includes gives it. === alone would never match NaN.