π Mastering indexOf in JavaScript: What Every Developer Should Know

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:
0is the first item1is 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!