indexOf in JavaScript

If you’re learning JavaScript, the indexOf method is one you’ll use often. It’s a simple but powerful way to find the position of an item in a string or an array.

🧠 Pro Tip: JavaScript counts from zeroβ€”the first item is always at index 0.


πŸ”Ž How indexOf Works

indexOf searches from left to right and returns the index of the first match. If no match is found, it returns -1.

βœ… Examples:

In Strings:

let text = "Hello world";
let index = text.indexOf("world"); // 6

In Arrays:

let fruits = ["apple", "banana", "orange"];
let index = fruits.indexOf("banana"); // 1

When Not Found:

let index = fruits.indexOf("grape"); // -1

πŸ€” Why Start at Zero?

In JavaScript (and most languages), counting begins at 0. So:

  • 0 is the first item
  • 1 is the second item
  • and so on…

Keep this in mind to avoid off-by-one bugs!


πŸš€ Why You Should Care

Whether you’re searching user input, filtering data, or building logicβ€”indexOf is a go-to method that helps keep your code clean and efficient.

Next time you need to check if something exists, let indexOf do the detective work.


🧠 Quick Quiz

1. What does indexOf return if the value isn’t found?

  • a) The first element
  • b) -1
  • c) The length of the array
  • d) Undefined

2. What will this return?

let animals = ["cat", "dog", "elephant"];
let index = animals.indexOf("dog");
  • a) 0
  • b) 1
  • c) 2
  • d) -1

✌️ Keep coding. Keep learning. More bite-sized JavaScript tips coming soon!


<
Previous Post
πŸš€ Empowering the Next Generation of Programmers: The Journey of Ekene Agunechemba
>
Next Post
🧠 Transforming Text with toUpperCase() in JavaScript