Table of Contents
What indexOf() Does
- Finds the position of a value: it searches from left to right and returns the index of the first match.
- Returns -1 when nothing matches: it does not throw an error.
- Leaves the original array alone: it only reads through it.
- Compares values strictly: the type has to match as well, so the number 5 is not the same as the string "5".
let fruits = ["apple", "banana", "mango", "banana"];
console.log(fruits.indexOf("banana")); // 1, the first match only
console.log(fruits.indexOf("grape")); // -1, not found
Syntax and Parameters
array.indexOf(valueToFind, fromIndex);
- valueToFind: the value you are searching for.
- fromIndex: the position where the search starts. This is optional, and it defaults to 0.
- A negative fromIndex: it counts from the end of the array.
let nums = [10, 20, 30, 20, 40]; console.log(nums.indexOf(20)); // 1 console.log(nums.indexOf(20, 2)); // 3, the search starts at index 2 console.log(nums.indexOf(40, -1)); // 4, the search starts at the last item
Checking the Result Correctly
Always compare with -1: this is the safe way to tell whether the value was found.
let colors = ["red", "green", "blue"];
let index = colors.indexOf("red");
if (index !== -1) {
console.log(`Found at position ${index}`);
} else {
console.log("Not found");
}
Avoid a simple truthy check: index 0 is a valid position, but it is also falsy.
let position = colors.indexOf("red"); // 0
console.log(!position); // true, which wrongly suggests "not found"
console.log(position !== -1); // true, the correct check
Practical Examples
Removing an item by its value:
let tasks = ["study", "gym", "sleep"];
let index = tasks.indexOf("gym");
if (index !== -1) {
tasks.splice(index, 1);
}
console.log(tasks); // ["study", "sleep"]
Finding every position of a value:
let letters = ["a", "b", "a", "c", "a"];
let positions = [];
let i = letters.indexOf("a");
while (i !== -1) {
positions.push(i);
i = letters.indexOf("a", i + 1);
}
console.log(positions); // [0, 2, 4]
Checking whether a value is new:
let seen = ["js", "css"];
if (seen.indexOf("html") === -1) {
seen.push("html");
}
console.log(seen); // ["js", "css", "html"]
Removing duplicates:
let nums = [1, 2, 2, 3, 3, 3]; let unique = nums.filter((n, index) => nums.indexOf(n) === index); console.log(unique); // [1, 2, 3]
indexOf() on Strings
Strings have their own indexOf(): it returns the position where a smaller piece of text first appears.
let sentence = "JavaScript is fun";
console.log(sentence.indexOf("Script")); // 4
console.log(sentence.indexOf("script")); // -1, because it is case-sensitive
console.log(sentence.indexOf("is")); // 11
Use lastIndexOf() to search from the end: it returns the position of the last match.
let path = "home/user/docs/file.txt";
let lastSlash = path.lastIndexOf("/");
console.log(path.slice(lastSlash + 1)); // "file.txt"
Things to Remember
It uses strict comparison: the number 1 and the string "1" are different.
console.log([1, 2, 3].indexOf("2")); // -1
console.log([1, 2, 3].indexOf(2)); // 1
It cannot find NaN: unlike includes().
console.log([NaN].indexOf(NaN)); // -1 console.log([NaN].includes(NaN)); // trueIt does not work well for objects: objects are compared by reference, not by their contents.
let users = [{ id: 1 }, { id: 2 }];
console.log(users.indexOf({ id: 2 })); // -1, because it is a different object
For objects, use findIndex(): write a condition that compares the property you care about.
console.log(users.findIndex(user => user.id === 2)); // 1
Common Mistakes
- Using a truthy check on the result: index 0 is valid, so compare with -1 instead.
- Searching for objects: indexOf() compares references, so use findIndex() instead.
- Mixing up types: searching for the string "5" in an array of numbers returns -1.
- Splicing with -1: splice(-1, 1) removes the last item, so always check the result first.
Conclusion
The indexOf() method gives you the position of the first match, or -1 when there is none. Remember to compare the result with -1 rather than using a truthy check, and use findIndex() whenever you are searching for objects or need a condition.
Frequently Asked Questions (FAQs)
1. What does indexOf() return if the value is not found?
2. Does indexOf() find all matches or only the first one?It returns -1.
3.What is the difference between indexOf() and includes()?Only the first one. To find every position, call it repeatedly with a fromIndex, as in the example above.
indexOf() returns the position, while includes() returns only true or false.
0 Comments