Skip to content
jshacks.dev
Fundamentals

JavaScript Array indexOf Explained With Clear Examples

Array indexOf() returns the first position of a value or -1. See how fromIndex, strict equality, NaN and sparse arrays change the result.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, npm, Node.js and Vite logos.

indexOf() returns a number that means two different things: a position when the value is found, and -1 when it is not. Code that writes if (list.indexOf(x)) treats the first element as "not found" because its index is 0, which is falsy, and treats a missing value as "found" because -1 is truthy. That one bug has shipped in more codebases than any other array mistake, and it is why indexOf() deserves a careful read even though it has existed since ES5. This post covers the arguments, the comparison rule, the cases where it quietly fails, and when includes() or findIndex() is the better call. Everything runs on Node.js 24. If you only need a yes or no, [the post on includes()](/library/javascript-array-includes) is the shorter path.

What indexOf() takes and returns

The signature is array.indexOf(searchElement, fromIndex). It scans from fromIndex toward the end and returns the index of the first element that is strictly equal to searchElement. If nothing matches, it returns -1.

ArgumentMeaningDefault
searchElementThe value to look fornone
fromIndexThe index to start scanning at0

The method never changes the array, and it never returns anything other than an integer from -1 up to length - 1.

JavaScript
const stack = ["a", "b", "c", "b"];

console.log(stack.indexOf("b"));
console.log(stack.indexOf("z"));
console.log(stack.indexOf("b", 2));
Text
1
-1
3

The first call finds the earlier "b" at index 1. The second finds nothing. The third starts scanning at index 2, skips the first "b", and finds the one at index 3. That third form is how you walk through every occurrence, which the next section shows.

Finding every occurrence

indexOf() returns only the first match, so a loop that moves fromIndex forward past each hit collects all of them.

JavaScript
const log = ["ok", "error", "ok", "error", "error"];
const hits = [];

let at = log.indexOf("error");
while (at !== -1) {
  hits.push(at);
  at = log.indexOf("error", at + 1);
}

console.log(hits);
Text
[ 1, 3, 4 ]

The comparison against -1 is explicit, which is the safe habit. A cleaner alternative is log.flatMap((v, i) => (v === "error" ? [i] : [])), which does the same in one pass without the manual cursor. Prefer the loop only when you need to stop early.

Negative fromIndex counts from the end

A negative fromIndex is an offset from the end of the array. Internally the method adds the array length to it, and if the result is still below zero it starts at 0.

JavaScript
const nums = [1, 2, 3, 4];

console.log(nums.indexOf(3, -2));
console.log(nums.indexOf(1, -2));
console.log(nums.indexOf(1, -100));
Text
2
-1
0

With four elements, -2 means "start at index 2", so 3 is found there and 1 is not. An offset larger than the length clamps to the start, which is why -100 still finds 1 at index 0. The scan always moves forward. A negative fromIndex changes where it starts, not the direction. To search backward you want [lastIndexOf()](/library/javascript-array-lastindexof).

Strict equality is the rule

indexOf() compares with ===. There is no type conversion, so a number does not match its string form, and two distinct objects never match even when their contents are identical.

JavaScript
const mixed = [1, "1", 2];
console.log(mixed.indexOf("1"));
console.log(mixed.indexOf(Number("2")));

const target = { id: 7 };
const items = [{ id: 7 }, target];
console.log(items.indexOf({ id: 7 }));
console.log(items.indexOf(target));
Text
1
2
-1
1

The object case trips people most. The literal { id: 7 } in the call creates a brand new object, which is not any element of the array. Only the saved reference target matches. When you need to match objects by a field, use findIndex() with a predicate, because indexOf() cannot take one.

NaN, -0 and sparse arrays

Strict equality gives indexOf() two quirks. NaN is never equal to anything, including itself, so indexOf() cannot find it. And it treats 0 and -0 as the same value.

JavaScript
console.log([NaN].indexOf(NaN));
console.log([NaN].includes(NaN));
console.log([0].indexOf(-0));
Text
-1
true
0

That is the main behavioral difference from includes(), which uses SameValueZero and finds NaN. If a list can contain NaN, indexOf() is the wrong tool.

Sparse arrays add a third quirk. indexOf() skips holes entirely, so a missing slot is not the same as a slot holding undefined.

JavaScript
const holes = [, 1];
const explicit = [undefined, 1];

console.log(holes.indexOf(undefined));
console.log(explicit.indexOf(undefined));
Text
-1
0

The first array has no property at index 0, so the scan never visits it. Sparse arrays come from new Array(5) and from deleting elements, and they are best avoided because most array methods treat holes inconsistently.

It works on array-likes too

The method is generic. It only needs a length and indexed properties, so you can borrow it for strings and arguments-style objects.

JavaScript
const pos = Array.prototype.indexOf.call("hello", "l");
console.log(pos);
Text
2

For strings you would normally call String.prototype.indexOf(), which accepts a multi-character substring. The array version matches one element at a time, so "hello" is treated as five single-character elements. The borrowed call is useful for a NodeList copy or an object like { length: 2, 0: "x", 1: "y" }, but converting with Array.from() first is clearer.

Choosing between indexOf, includes and findIndex

The three methods answer different questions, and picking the right one removes the -1 handling.

You wantUseReturns
A yes or no for a primitiveincludes()true or false
The position of a primitiveindexOf()index or -1
The position by condition or object fieldfindIndex()index or -1
The element itself by conditionfind()element or undefined

We reach for includes() first because a boolean cannot be misread. indexOf() earns its place when you need the position to slice or splice, as in list.splice(list.indexOf(x), 1). That example has a sharp edge: if x is missing, indexOf() returns -1, and splice(-1, 1) removes the last element. Guard the call:

JavaScript
const queue = ["a", "b", "c"];
const i = queue.indexOf("z");
if (i !== -1) queue.splice(i, 1);

console.log(queue);
Text
[ 'a', 'b', 'c' ]

Without the guard, the last element would have been removed, which is the kind of silent data loss that survives code review because the line looks fine.

Where indexOf stops being the right tool

If you search the same large array many times for different values, each call scans from the start, so the cost grows with both the array size and the number of lookups. Building a Set or a Map once makes each later lookup a single hash check instead of a scan. For a handful of lookups on a short list, the array method is simpler and fast enough, and we would not add a Set for it.

It also cannot match by structure. Comparing objects, dates or arrays by content needs findIndex() with your own equality, or a serialization step you control. And if the list may contain NaN, use includes() or findIndex(Number.isNaN).

The method is defined in the ECMAScript specification under Array.prototype.indexOf, and MDN documents it on the Array.prototype.indexOf page. For the reverse scan, read [the post on lastIndexOf()](/library/javascript-array-lastindexof).

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.