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