JavaScript Array indexOf() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Find index

What You’ll Learn

The indexOf() method returns the first index where a value appears, or -1 if it is missing. Optional fromIndex controls where the search starts. This tutorial covers syntax, five examples, strict equality, and how indexOf() compares to includes() and lastIndexOf().

01

Syntax

indexOf(val)

02

First match

Left to right

03

Not found

-1

04

Strict

===

05

fromIndex

Start offset

06

ES5

Wide support

Introduction

When you need the position of a value—not just whether it exists—indexOf() is the classic array search method. It scans from the start (or from fromIndex) and stops at the first match.

For a simple yes/no check, modern code often prefers includes(). Use indexOf() when the index itself matters: splicing, inserting nearby, or deduplicating.

Understanding the indexOf() Method

array.indexOf(searchElement, fromIndex?) compares each element with strict equality (===). The return value is a zero-based index or -1.

Duplicate values are common. indexOf always returns the first occurrence. To find the last match, use lastIndexOf().

💡
Beginner Tip

Index 0 is valid, so never test with if (index). Use index !== -1 or includes() instead.

📝 Syntax

General form of Array.prototype.indexOf:

JavaScript
array.indexOf(searchElement, fromIndex)

Parameters

  • searchElement — value to locate.
  • fromIndex — optional; index to start searching (default 0).

Return value

  • First matching index (0 or greater).
  • -1 if no match.
  • Original array unchanged.

Common patterns

  • arr.indexOf("blue") — find first index.
  • arr.indexOf("blue", 2) — search from index 2.
  • arr.indexOf(x) !== -1 — membership test (prefer includes).
  • arr.filter((v, i, a) => a.indexOf(v) === i) — dedupe pattern.

⚡ Quick Reference

GoalCode
First index of valuearr.indexOf(value)
Search from indexarr.indexOf(value, fromIndex)
Not found-1
Boolean checkarr.includes(value)
Last occurrencearr.lastIndexOf(value)

📋 indexOf() vs includes() vs lastIndexOf() vs findIndex()

Choose based on whether you need an index, a boolean, direction, or a custom test.

indexOf
first index

Exact value

includes
true / false

Membership

lastIndexOf
last index

Right to left

findIndex
predicate

Custom test

Examples Gallery

Open DevTools Console (F12) or use Try-it labs. Example N maps to ?tryit=N.

📚 Getting Started

Locate values and handle missing items.

Example 1 — Find the Index of a Value

Search a color array for the first occurrence of "green".

JavaScript
const colors = ["red", "blue", "green", "yellow", "blue"];

console.log(colors.indexOf("green"));
// 2
Try It Yourself

How It Works

"green" sits at index 2 (zero-based counting).

Example 2 — Search with fromIndex

Skip the first "blue" by starting the search at index 2.

JavaScript
const colors = ["red", "blue", "green", "yellow", "blue"];

console.log(colors.indexOf("blue"));
// 1 (first "blue")

console.log(colors.indexOf("blue", 2));
// 4 (second "blue")
Try It Yourself

How It Works

Without fromIndex, the first "blue" at index 1 wins. Starting at 2 finds the later duplicate at index 4.

📈 Practical Patterns

Missing values, type checks, and deduplication.

Example 3 — Returns -1 When Not Found

Always handle the not-found case explicitly.

JavaScript
const colors = ["red", "blue", "green"];

const index = colors.indexOf("purple");

console.log(index);
// -1

if (index !== -1) {
  console.log("Found at", index);
} else {
  console.log("Not in array");
}
// Not in array
Try It Yourself

How It Works

-1 means no match. Because index 0 is valid, use !== -1, not a truthy check on the index.

Example 4 — Strict Equality (Number vs String)

The array holds the number 3, not the string "3".

JavaScript
const numbers = [1, 2, 3, 4, 5];

console.log(numbers.indexOf(3));
// 2

console.log(numbers.indexOf("3"));
// -1
Try It Yourself

How It Works

indexOf uses ===. Type coercion does not happen—convert types first if you need loose matching.

Example 5 — Remove Duplicates with filter + indexOf

Keep only the first occurrence of each value.

JavaScript
const colors = ["red", "blue", "green", "yellow", "blue"];

const unique = colors.filter(
  (value, index, array) => array.indexOf(value) === index
);

console.log(unique);
// ["red", "blue", "green", "yellow"]
Try It Yourself

How It Works

An item is kept only when its index equals the first index of that value. Modern code often uses [...new Set(arr)] instead, but this pattern teaches how indexOf works.

🚀 Common Use Cases

  • Find position — locate an item before splice or insert.
  • Membership via indexindexOf(x) !== -1 (or use includes).
  • Deduplication — filter where indexOf(v) === i.
  • Skip processed items — pass fromIndex to find next duplicate.
  • Simple lookups — tags, enums, or menu item positions.
  • Legacy compatibility — widely supported ES5 search API.

🧠 How indexOf() Runs

1

Resolve fromIndex

Default 0; handle negative offsets from end.

Start
2

Compare each slot

Strict equality against searchElement.

Scan
3

Return first match

Stop and return index on first hit.

Found
4

Or return -1

No match after full forward scan.

📝 Notes

  • Returns first match only—use lastIndexOf for last.
  • Not found → -1 (index 0 is valid).
  • Strict ===; does not find NaN.
  • Objects match by reference, not deep equality.
  • For boolean checks, prefer includes() in modern code.
  • ES5—excellent support including IE9+.

Browser & Runtime Support

Array.prototype.indexOf() has been available since ES5 (2009). It is one of the oldest and most widely supported array search methods.

Baseline · ES5

Array.prototype.indexOf()

Supported in Chrome 1+, Firefox 1.5+, Safari 3+, Edge (all versions), IE 9+, and all modern Node.js versions.

99% Universal support
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
Array.indexOf() Excellent

Bottom line: Safe to use everywhere except very old IE8 environments. No polyfill needed for modern projects.

Conclusion

indexOf() answers “where is the first occurrence?” with an index or -1. Pair it with careful !== -1 checks, or use includes() when you only need true/false.

Next, learn join() to combine array elements into a single string.

💡 Best Practices

✅ Do

  • Compare with !== -1 for existence checks
  • Use includes() when you only need boolean
  • Pass fromIndex to skip earlier matches
  • Use lastIndexOf for the last occurrence
  • Match types strictly (number vs string)

❌ Don’t

  • Test with if (index)—0 is falsy
  • Expect to find NaN with indexOf
  • Assume deep equality for objects
  • Use indexOf when findIndex(fn) fits better
  • Forget duplicates—only first index is returned

Key Takeaways

Knowledge Unlocked

Five things to remember about Array.indexOf()

Find the first index of a value in any array.

5
Core concepts
📍 02

First index

Left to right.

Direction
−1 03

Not found

-1 return.

Sentinel
📐 04

Strict

=== compare.

Types
🌟 05

ES5

IE9+.

Support

❓ Frequently Asked Questions

indexOf() returns the index of the first matching element in the array. If the value is not found, it returns -1.
indexOf() returns a number (index or -1). includes() returns true or false. For simple membership checks, includes() reads more clearly.
It returns -1. Always compare with !== -1 (or use includes() for a boolean).
No. indexOf() uses strict equality and never matches NaN. Use includes(NaN) or findIndex with Number.isNaN instead.
fromIndex sets where the search starts. Default is 0. Negative values count from the end of the array.
indexOf() is ES5 (2009). It works in all modern browsers and has been supported in Internet Explorer 9+.
Did you know?

Strings also have indexOf() for substring search: "hello".indexOf("ell") returns 1. Array indexOf compares whole elements, not substrings within them.

Continue to join()

Learn how to combine array elements into one string with a separator.

join() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful