🔍

indexOf()

🤔
💨
Let's play detective! We'll search for items in our train!

The indexOf() Method

The indexOf() method tells you where an item is in your array.

It returns the index (position) of the item. If the item isn't found, it returns -1.

💡
💨

How indexOf() Works

1const fruits = ["🍎", "🍌", "🍊", "🍇"];
2
3fruits.indexOf("🍌"); // 1 (found at index 1)
4fruits.indexOf("🍊"); // 2 (found at index 2)
5fruits.indexOf("🥝"); // -1 (not found!)
6
7// It finds the FIRST occurrence
8const letters = ["a", "b", "a", "c"];
9letters.indexOf("a"); // 0 (first "a")
🤔
💨

What Does -1 Mean?

When indexOf() returns -1, it means "not found"!

Pro tip: -1 is used because 0 is a valid index (the first item). We needed a number that couldn't be confused with a real position!

🎮

Try It Yourself!

Click on a fruit to find its position in the array! Watch the detective search.

[
🍎
[0]
🍌
[1]
🍊
[2]
🍇
[3]
🍓
[4]
]
length: 5