Mastering the indexOf() Method in JavaScript

Introduction

The indexOf() method in JavaScript is used to find the first occurrence of a specified value within a string or an array. It returns the index of that occurrence, or -1 if the value is not found. 🧠

📌 What is indexOf()?

indexOf() searches from left to right and stops at the first match it finds. It’s case-sensitive for strings and uses strict equality (===) for arrays.

  • 🔍 Works on both strings and arrays.
  • 📜 Returns the index of the first occurrence.
  • ❌ Returns -1 if no match is found.

💡 Syntax

Basic Syntax

// For strings
string.indexOf(searchValue, fromIndex)

// For arrays
array.indexOf(searchElement, fromIndex)

Parameters:

  • searchValue / searchElement — The value to search for.
  • fromIndex — Optional starting position for the search (default is 0).

🧵 Example with Strings

String indexOf()

const text = "Hello World";
console.log(text.indexOf("World")); // 6
console.log(text.indexOf("o"));     // 4
console.log(text.indexOf("x"));     // -1

📦 Example with Arrays

Array indexOf()

const fruits = ["Apple", "Banana", "Mango", "Banana"];
console.log(fruits.indexOf("Banana")); // 1
console.log(fruits.indexOf("Orange")); // -1

➡️ Using fromIndex Parameter

Using fromIndex

const numbers = [1, 2, 3, 2, 4];
console.log(numbers.indexOf(2));      // 1
console.log(numbers.indexOf(2, 2));   // 3

⚠️ Important Notes

Note

For strings, indexOf() is case-sensitive, so "Hello".indexOf("h") will return -1. For arrays, it uses strict equality, so ["2"].indexOf(2) returns -1.

📊 Quick Reference Table

TypeExampleResult
String"Hello".indexOf("H")0
Array[1, 2, 3].indexOf(2)1
Not Found[1, 2, 3].indexOf(4)-1
>>"indexOf() is your quick locator — it tells you exactly where your target value lives or if it’s missing." 🔍

🔥 Summary

The indexOf() method is a simple and reliable way to locate values in strings and arrays. Just remember that it finds only the first match and that comparisons are case-sensitive for strings and strict for arrays.