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