What is indexOf()?

indexOf(value, fromIndex?) returns the first index where a value appears in an array or string, or -1 if it is not found; lastIndexOf searches from the end.

How it compares

Arrays use strict equality (===). That means:

  • Objects are matched only if it is the exact same reference.
  • NaN is never found, because NaN !== NaN.

When to use it

  • When you actually need the position: to remove an item with splice, insert next to it, or find a substring's start.
  • Strings: "hello".indexOf("l") is 2.

When to use something else

  • Just checking existence: includes reads better and handles NaN.
  • Matching by a condition (objects, partial matches): findIndex(item => item.id === 3).
  • Searching from the end by condition: findLastIndex.

Common bug

if (list.indexOf(x)) is wrong: index 0 is falsy (so a match at the start looks like "not found"), and -1 is truthy. Always compare with -1, or use includes.

Removing duplicates

list.filter((x, i) => list.indexOf(x) === i) keeps only the first occurrence of each value. It is O(n²), so for large arrays [...new Set(list)] is far faster.

Code example

js
1const colors = ["red", "green", "blue", "green"];
2
3console.log(colors.indexOf("green")); // 1
4console.log(colors.lastIndexOf("green")); // 3
5console.log(colors.indexOf("purple")); // -1
6console.log(colors.indexOf("green", 2)); // 3 (search starts at index 2)
7
8// The classic bug: index 0 is falsy
9if (colors.indexOf("red")) console.log("never logged even though red is there");
10if (colors.indexOf("red") !== -1) console.log("red found at index 0");
11
12// Remove a specific item by position
13const tags = ["js", "css", "html"];
14const i = tags.indexOf("css");
15if (i !== -1) tags.splice(i, 1);
16console.log(tags); // ["js", "html"]
17
18// Objects need findIndex
19const users = [{ id: 1 }, { id: 2 }];
20console.log(users.indexOf({ id: 2 }), users.findIndex((u) => u.id === 2)); // -1 1
21
22// Strings
23console.log("hello world".indexOf("o"), "hello world".lastIndexOf("o")); // 4 7

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app