A beginner-friendly deep dive into JavaScript’s powerful indexOf() method — from strings to arrays, and real-world examples.
🔍 What is indexOf() in JavaScript?
The indexOf() method is used to find the position (index) of a specific element inside a string or array. If it’s not found, it returns -1.
🧪 Syntax
For Strings:
string.indexOf(searchValue, startIndex)
For Arrays:
array.indexOf(searchElement, fromIndex)
📘 Using indexOf() with Strings
const text = "JavaScript is amazing";
console.log(text.indexOf("Script")); // 4
✅ Case Sensitivity
console.log(text.indexOf("script")); // -1
🔁 First Occurrence
const sentence = "I love JavaScript because JavaScript is fun!";
console.log(sentence.indexOf("JavaScript")); // 7
🕵️♂️ Find All Occurrences
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
🎯 Check if an Element Exists
if (fruits.indexOf("banana") !== -1) {
console.log("Banana is in the list!");
}
🧠 indexOf()
vs includes()
| Feature | indexOf() | includes() |
| -------- | ------------- | --------------- |
| Returns | Index or -1 | true / false |
| Use Case | Find position | Check existence |
⚡ Performance Tip
// Simpler check
arr.includes("item");
// More flexible
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
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")); // 7
✅ Summary
- Works on strings and arrays
- Returns index if found, -1 if not
- Case-sensitive
- Use includes() for existence check only
🧠 FAQs
Q: Can indexOf() find objects in an array?
A: No, only primitive values like strings, numbers.
Q: What if multiple matches exist?
A: It returns the first index only.
Q: Does indexOf() modify the array or string?
A: No, it is non-mutating.
🔥 Want More?
Read the full blog with images and formatting here:
👉 https://webcodingwithankur.blogspot.com/2025/07/indexof-in-javascript-complete-guide.html
Top comments (0)