indexOf, lastIndexOf and includes in JavaScript
Beginner · 3 min read
"Is this item in the list?" and "where is it?" are two of the most common questions you ask an array. Is this email already on the mailing list? Which position is the selected tab? Where did this reading appear last? JavaScript has three small methods for these: indexOf, lastIndexOf and includes.
In this tutorial you will use all three, see what each one gives back when the value isn't there, and then try them on NaN, where they disagree. You should know what an array, an index and === are.
Strict equality, and the odd one out
=== is strict equality. It is true only when both sides are the same type and the same value, so 20 === '20' is false.
There is one value that isn't even equal to itself: NaN, short for "not a number". You get it from maths that has no answer, like 0 / 0 or Number('abc').
console.log(20 === '20'); // false
console.log(NaN === NaN); // false
console.log(Number.isNaN(0 / 0)); // true
Because NaN === NaN is false, any search that uses === can never find a NaN. Number.isNaN is the right way to test for it.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
9 indexOf, lastIndexOf and includes
easyFind a value's first and last position, and answer whether it is present at all. Then try all three against NaN.
Stuck? Three hints, smallest first
- 1.
indexOfreturns a position or-1;includesreturns a boolean. - 2. They compare differently. One uses
===, the other treatsNaNas equal to itself. - 3. Both take a second argument saying where to start looking.
Step 1: find the first position
indexOf(value) walks from the start and gives the index of the first match.
const readings = [10, 20, 30, 20, NaN];
console.log(readings.indexOf(20)); // 1
console.log(readings.indexOf(99)); // -1
20 appears twice, at index 1 and index 3. indexOf stops at the first one. When there is no match it returns -1, not undefined. Since -1 is never a real index, it is a safe "not found" signal.
Step 2: find the last position
lastIndexOf does the same search from the end.
const readings = [10, 20, 30, 20, NaN];
console.log(readings.lastIndexOf(20)); // 3
Step 3: start the search later
Both methods take a second argument: the index to start from.
const readings = [10, 20, 30, 20, NaN];
console.log(readings.indexOf(20, 2)); // 3
Starting at index 2 skips the first 20, so the next one, at index 3, is found.
Step 4: just ask "is it there?"
Often you don't care where the item is, only whether it is there. Before includes existed, people wrote indexOf(x) !== -1. includes says the same thing in plain words and returns true or false.
const readings = [10, 20, 30, 20, NaN];
console.log(readings.indexOf(30) !== -1); // true
console.log(readings.includes(30)); // true
console.log(readings.includes(99)); // false
A common slip is writing if (readings.indexOf(10)). The index of 10 is 0, and 0 counts as false in an if, so the check fails for the very first item. includes avoids that trap.
Step 5: no type conversion
Neither method converts types. A string '20' is not the number 20.
const readings = [10, 20, 30, 20, NaN];
console.log(readings.indexOf('20')); // -1
console.log(readings.includes('20')); // false
This often bites when values come from a form or a URL, which always give you strings. Convert first, for example with Number(value).
Step 6: searching for NaN
Here is where the two part company.
const readings = [10, 20, 30, 20, NaN];
console.log(readings.indexOf(NaN)); // -1
console.log(readings.includes(NaN)); // true
console.log(readings.findIndex(Number.isNaN)); // 4
indexOf compares with ===, and NaN === NaN is false, so it can never find one. includes uses a slightly different rule, called SameValueZero, which is like === except that it treats NaN as equal to itself. So includes finds it.
If you need the position of a NaN, use findIndex with a test function. findIndex(Number.isNaN) calls Number.isNaN on each item and returns the index of the first one that passes.
The full solution
The panel searches one array of readings with all three methods, including the NaN at the end and a string '20'. Press Run to see each answer.
const readings = [10, 20, 30, 20, NaN];
console.log('indexOf(20) :', readings.indexOf(20));
console.log('lastIndexOf(20) :', readings.lastIndexOf(20));
console.log('indexOf(99) :', readings.indexOf(99), '<- the miss value is -1');
console.log('includes(30) :', readings.includes(30));
console.log('--- NaN is where the two part company ---');
console.log('indexOf(NaN) :', readings.indexOf(NaN), '<- === says NaN !== NaN');
console.log('includes(NaN) :', readings.includes(NaN), '<- SameValueZero says it is');
console.log('findIndex is the other way to locate a NaN:', readings.findIndex(Number.isNaN));
console.log("indexOf('20') :", readings.indexOf('20'), '<- no coercion');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('indexOf finds the first match', readings.indexOf(20), 1);
test('lastIndexOf finds the last', readings.lastIndexOf(20), 3);
test('a miss is -1, not undefined', readings.indexOf(99), -1);
test('includes answers with a boolean', readings.includes(30), true);
test('indexOf cannot find NaN', readings.indexOf(NaN), -1);
test('includes can', readings.includes(NaN), true);
test('findIndex can locate it as well', readings.findIndex(Number.isNaN), 4);
test('indexOf does not coerce a string to a number', readings.indexOf('20'), -1);
test('a start index skips the earlier matches', readings.indexOf(20, 2), 3);
The two methods use different equality. indexOf uses strict equality, and NaN === NaN is false, so it can never find one. includes uses SameValueZero, which treats NaN as equal to itself — that is the entire reason it was added, beyond reading better than !== -1.
The two also share a limitation: they compare by identity, so [{ id: 1 }].includes({ id: 1 }) is false. For objects you want some or find with a predicate. Neither coerces, which is why indexOf('20') misses a stored 20.
Common mistakes
- Treating
indexOfas true or false. A match at index0is falsy and a miss,-1, is truthy. Compare with-1, or useincludes. - Searching for objects.
[{ id: 1 }].includes({ id: 1 })isfalse, because two separate objects are never===. Usesomeorfindwith a test function. - Searching for a number with a string.
indexOf('20')won't find20. Convert the value first.
Try it yourself
- Write
countOf(xs, value)that counts how many timesvalueappears, usingindexOfwith a start index in a loop. - Check whether
'banana'is in['apple', 'Banana']without caring about upper or lower case. - Find the position of the last
NaNin[NaN, 1, NaN, 2].