Searching with indexOf
Learn to find an element's position with indexOf.
Finding an element position with indexOf
The indexOf method returns the first position (index) of an element in the array. If it cannot find it, it returns -1.
Example: ["apple", "pear", "banana"].indexOf("pear") returns 1. The search goes front to back; the first match is returned.
A start index can be passed as a second argument: arr.indexOf(x, 2) starts searching from index 2.
When not found, -1
When indexOf cannot find the element it returns -1. So to check whether an element exists, you write if (arr.indexOf(x) !== -1).
Example: ["a", "b"].indexOf("z") returns -1 because "z" is not in the array.
This pattern is common, but newer code has a more readable alternative: the includes method returns true/false directly.
Exercise Find a city position in the cities array
Create an array named cities with at least four city strings. Use cities.indexOf to find a city's position and print the result with console.log.
Show example solution
Write the array, then search for a city with cities.indexOf and print the result with console.log.
Example solution:
const cities = ["Istanbul", "Ankara", "Izmir", "Bursa"];
const pos = cities.indexOf("Izmir");
console.log(pos);
Test yourself
-
What does this code print?
const fruits = ["apple", "pear", "banana"]; console.log(fruits.indexOf("banana"));- 1
- 3
- 2
- -1
Show answer
2 — Correct. "banana" is at index 2; indexOf returns 2.
-
Find the position of blue
const colors = ["red", "blue", "green"]; const pos = colors.indexOf(____); console.log(pos);Show answer
const colors = ["red", "blue", "green"]; const pos = colors.indexOf("blue"); console.log(pos); -
Match indexOf behaviors
- indexOf when not found
- returns -1
- indexOf first match
- returns its index
- indexOf second argument
- start index