🧠 How to Use indexOf() in JavaScript – Complete Guide with Examples
🔍 What is indexOf() in JavaScript?
The indexOf() method in JavaScript is used to find the position (index) of a specific element within a string or array. If the item is not found, it returns -1.
🧪 Syntax
For Strings:
string.indexOf(searchValue, startIndex)
For Arrays:
array.indexOf(searchElement, fromIndex)
📘 How indexOf() Works in Strings
const text = "JavaScript is amazing";
console.log(text.indexOf("Script")); // Output: 4
✅ Case Sensitivity:
console.log(text.indexOf("script")); // Output: -1
Note: indexOf() is case-sensitive.
🔁 Finding the First Occurrence
const sentence = "I love JavaScript because JavaScript is fun!";
console.log(sentence.indexOf("JavaScript")); // Output: 7
🕵️♂️ Find All Occurrences in a String
const str = "JS is cool. JS is powerful. JS is everywhere!";
let index = str.indexOf("JS");
while (index !== -1) {
console.log("Found at:", index);
index = str.indexOf("JS", index + 1);
}
🧾 Using indexOf() with Arrays
const fruits = ["apple", "banana", "cherry", "apple"];
console.log(fruits.indexOf("apple")); // 0
console.log(fruits.indexOf("cherry")); // 2
const numbers = [1, 5, 10, 15];
console.log(numbers.indexOf(10)); // 2
console.log(numbers.indexOf(20)); // -1
🎯 Use indexOf() to Check If an Element Exists
if (fruits.indexOf("banana") !== -1) {
console.log("Banana is in the list!");
}
🧠 Difference Between indexOf() and includes()
| Feature | indexOf() |
includes() |
|---|---|---|
| Return Type | Index (or -1) | true / false |
| Use Case | Find position | Check existence |
⚡ Performance Tip
// Faster and cleaner
arr.includes("item");
// More flexible if you need index
arr.indexOf("item") !== -1
📌 Real-World Use Case
const input = "Learn JavaScript the fun way!";
const term = "JavaScript";
if (input.indexOf(term) !== -1) {
console.log(`The term "${term}" exists in the sentence.`);
}
❓ Common Interview Question
Q: How can you check if a string contains a word without using regex?
A: Use .indexOf() and compare the result with -1.
🧩 Practice Challenge
Problem: Write a function that finds if the word "React" exists in a sentence and returns its position.
function findReact(sentence) {
return sentence.indexOf("React");
}
console.log(findReact("I love React and JavaScript")); // Output: 7
✅ Summary
- Works On: Strings and Arrays
- Returns: Index or -1
- Case-Sensitive: Yes
- Alternative:
includes()for true/false checks
🔗 Related Posts:
- Tailwind + React + Vite: A Full Setup and Starter Template
- What’s New in React Router 7 ? Features & Setup Guide (2025)
- How to Fix npx tailwindcss init Error: “Could Not Determine Executable to Run”
🧠 Frequently Asked Questions (FAQs)
❓ Can indexOf() find objects in an array?
No. It only works for primitive values.
❓ What happens if there are multiple matches?
It returns only the first index found.
❓ Does indexOf() modify the original array?
No. It is a non-mutating method.

Comments
Post a Comment