DEV Community

WebTechnology Tutorials
WebTechnology Tutorials

Posted on • Originally published at webcodingwithankur.blogspot.com

1

How to Use indexOf() in JavaScript – Complete Guide with Examples

Learn how to use indexOf() in JavaScript with syntax

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)

Enter fullscreen mode Exit fullscreen mode

For Arrays:

array.indexOf(searchElement, fromIndex)

Enter fullscreen mode Exit fullscreen mode

📘 Using indexOf() with Strings

const text = "JavaScript is amazing";
console.log(text.indexOf("Script")); // 4

Enter fullscreen mode Exit fullscreen mode

Case Sensitivity

console.log(text.indexOf("script")); // -1

Enter fullscreen mode Exit fullscreen mode

🔁 First Occurrence

const sentence = "I love JavaScript because JavaScript is fun!";
console.log(sentence.indexOf("JavaScript")); // 7

Enter fullscreen mode Exit fullscreen mode

🕵️‍♂️ 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);
}

Enter fullscreen mode Exit fullscreen mode

🧾 Using indexOf() with Arrays

const fruits = ["apple", "banana", "cherry", "apple"];
console.log(fruits.indexOf("apple")); // 0
console.log(fruits.indexOf("cherry")); // 2

Enter fullscreen mode Exit fullscreen mode
const numbers = [1, 5, 10, 15];
console.log(numbers.indexOf(10)); // 2
console.log(numbers.indexOf(20)); // -1

Enter fullscreen mode Exit fullscreen mode

🎯 Check if an Element Exists

if (fruits.indexOf("banana") !== -1) {
  console.log("Banana is in the list!");
}

Enter fullscreen mode Exit fullscreen mode

🧠 indexOf() vs includes()

| Feature  | indexOf()     | includes()      |
| -------- | ------------- | --------------- |
| Returns  | Index or -1   | true / false    |
| Use Case | Find position | Check existence |

Enter fullscreen mode Exit fullscreen mode

Performance Tip

// Simpler check
arr.includes("item");

// More flexible
arr.indexOf("item") !== -1

Enter fullscreen mode Exit fullscreen mode

📌 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.`);
}

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

Top comments (0)

Feature flag article image

Create a feature flag in your IDE in 5 minutes with LaunchDarkly’s MCP server ⏰

How to create, evaluate, and modify flags from within your IDE or AI client using natural language with LaunchDarkly's new MCP server. Follow along with this tutorial for step by step instructions.

Read full post

👋 Kindness is contagious

Explore this insightful piece, celebrated by the caring DEV Community. Programmers from all walks of life are invited to contribute and expand our shared wisdom.

A simple "thank you" can make someone’s day—leave your kudos in the comments below!

On DEV, spreading knowledge paves the way and fortifies our camaraderie. Found this helpful? A brief note of appreciation to the author truly matters.

Let’s Go!