JavaScriptEasy
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.
NaNis never found, becauseNaN !== 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")is2.
When to use something else
- Just checking existence:
includesreads better and handlesNaN. - 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"];23console.log(colors.indexOf("green")); // 14console.log(colors.lastIndexOf("green")); // 35console.log(colors.indexOf("purple")); // -16console.log(colors.indexOf("green", 2)); // 3 (search starts at index 2)78// The classic bug: index 0 is falsy9if (colors.indexOf("red")) console.log("never logged even though red is there");10if (colors.indexOf("red") !== -1) console.log("red found at index 0");1112// Remove a specific item by position13const tags = ["js", "css", "html"];14const i = tags.indexOf("css");15if (i !== -1) tags.splice(i, 1);16console.log(tags); // ["js", "html"]1718// Objects need findIndex19const users = [{ id: 1 }, { id: 2 }];20console.log(users.indexOf({ id: 2 }), users.findIndex((u) => u.id === 2)); // -1 12122// Strings23console.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.