Skip to content
jshacks.dev
Fundamentals

JavaScript Array lastIndexOf Explained With Examples

Array lastIndexOf() returns the final position of a value or -1, scanning backward. See how fromIndex works, including negative values, with exact output.

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

lastIndexOf() is the method people reach for when they want the final occurrence of something, and then its second argument undoes them: fromIndex is where the backward scan starts, so passing a position meant as "search after this" returns the wrong answer. The method is small, but its argument handling is the least intuitive of the search methods, and its comparison rule is the same strict equality that makes indexOf() blind to NaN. This post covers the signature, the direction of the scan, how negative offsets resolve, and where a different method is better. Examples run on Node.js 24. For the forward version, read [the post on indexOf()](/library/javascript-array-indexof).

What lastIndexOf() takes and returns

The signature is array.lastIndexOf(searchElement, fromIndex). It scans from fromIndex toward index 0 and returns the index of the first strictly equal element it meets, which is the last one in array order. If none match, it returns -1.

ArgumentMeaningDefault
searchElementThe value to look fornone
fromIndexThe index to start the backward scan fromlength - 1
JavaScript
const trail = ["home", "docs", "api", "docs", "faq"];

console.log(trail.lastIndexOf("docs"));
console.log(trail.indexOf("docs"));
console.log(trail.lastIndexOf("blog"));
Text
3
1
-1

The same value appears at index 1 and 3. indexOf() reports the first, lastIndexOf() the last. A missing value gives -1 in both.

fromIndex is where the backward scan begins

The second argument is not a lower bound. The scan starts at fromIndex and moves toward the front, so elements after that position are never examined.

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

console.log(marks.lastIndexOf("a", 3));
console.log(marks.lastIndexOf("a", 1));
console.log(marks.lastIndexOf("a", 0));
console.log(marks.lastIndexOf("c", 2));
Text
2
0
0
-1

With fromIndex of 3, the scan skips index 4 and finds the "a" at index 2. With 1, it goes back to index 0. The last line shows the trap: "c" is at index 3, which is past the starting point, so it is not found. If you wanted to search "only after position 2" you cannot express that with this method, and you would slice first.

Negative fromIndex counts from the end

A negative value is converted by adding the array length. The result is the starting position of the backward scan. If the sum is still negative, nothing is searched and the result is -1.

JavaScript
const n = [5, 1, 5, 2];

console.log(n.lastIndexOf(5, -1));
console.log(n.lastIndexOf(5, -2));
console.log(n.lastIndexOf(5, -3));
console.log(n.lastIndexOf(5, -5));
Text
2
2
0
-1

With length 4, -1 becomes 3, -2 becomes 2, -3 becomes 1, and -5 becomes -1, which is before the start. So -3 starts at index 1, finds nothing at 1, and continues to index 0 where the 5 is. The -5 case returns -1 outright.

Compare that with indexOf(), where a too-negative offset clamps to 0 and still searches the whole array. Here it does the opposite: an offset past the front searches nothing. That asymmetry is the main thing to remember.

Strict equality and its blind spots

lastIndexOf() uses ===, so it shares every limitation of indexOf().

JavaScript
const data = [NaN, 1, "1", { id: 1 }];

console.log(data.lastIndexOf(NaN));
console.log(data.lastIndexOf(1));
console.log(data.lastIndexOf("1"));
console.log(data.lastIndexOf({ id: 1 }));
Text
-1
1
2
-1

NaN is never found, because NaN === NaN is false. Numbers and numeric strings are different values. And a fresh object literal never equals the stored object, so only a saved reference would match. For NaN and for object fields, use findLastIndex(), which takes a predicate.

A better tool when you need a condition

findLastIndex() runs a function from the end and returns the index of the first element it accepts. It arrived in ES2023 and works in Node.js 18 and later.

JavaScript
const events = [
  { type: "open", at: 1 },
  { type: "close", at: 2 },
  { type: "open", at: 3 },
];

const last = events.findLastIndex((e) => e.type === "open");
console.log(last);
console.log(events.findLast((e) => e.type === "open"));
Text
2
{ type: 'open', at: 3 }

findLast() returns the element, findLastIndex() the position. Both treat the array as a list of things to test rather than values to compare, so they are the answer for objects, NaN and any rule more interesting than equality. The older method remains right for plain primitives: the call is shorter and needs no callback.

Common uses

Two jobs fit lastIndexOf() well. The first is removing the final occurrence of a value, with a guard for the missing case.

JavaScript
const stack = ["a", "b", "a", "c"];
const at = stack.lastIndexOf("a");

if (at !== -1) stack.splice(at, 1);
console.log(stack);
Text
[ 'a', 'b', 'c' ]

The -1 check matters: splice(-1, 1) removes the last element, so an unguarded call on a missing value deletes the wrong item.

The second is detecting duplicates. If the first and last positions of a value differ, it occurs more than once.

JavaScript
const ids = [4, 9, 4, 7];

const dupes = ids.filter((id, i) => ids.indexOf(id) !== ids.lastIndexOf(id) && ids.indexOf(id) === i);
console.log(dupes);
Text
[ 4 ]

That works, but it scans the array twice per element, so the cost grows with the square of the length. For a long list, count occurrences in a Map instead. We treat the two-index trick as fine for tens of items and wrong beyond that.

Array-likes and strings

lastIndexOf() is generic, so it works on any object with a length. For text, the string method of the same name is the one you want, because it matches substrings.

JavaScript
console.log(Array.prototype.lastIndexOf.call("banana", "a"));
console.log("banana".lastIndexOf("an"));
Text
5
3

The array version looked at single characters and found the last "a" at index 5. The string version matched the two-character substring "an" and found it starting at index 3. Use the string method for text. A fuller look at that API is in [the post on string indexOf()](/library/javascript-string-indexof).

A mistake worth naming: searching "after" a position

The argument name invites a misreading. In many languages a similar parameter means "start of the search range", and a reader who has used indexOf() assumes the same shape here. It is the opposite end. If you have a cursor at position p and want the last match at or before it, lastIndexOf(value, p) is exactly right. If you want the last match anywhere after p, you can call lastIndexOf(value) and then check that the result is greater than p.

JavaScript
const path = ["root", "src", "lib", "src", "test"];
const cursor = 2;

const last = path.lastIndexOf("src");
console.log(last > cursor ? last : -1);
console.log(path.lastIndexOf("src", cursor));
Text
3
1

The first form answers "is there a src after the cursor", and the second answers "what is the nearest src at or before it". Both are useful. Naming the variables for the question you are asking is the cheapest way to avoid mixing them up.

Why the method exists alongside findLastIndex

It is fair to ask why a method this limited survives next to findLastIndex(). The answer is that for primitives it is shorter, it has been in every engine since ES5, and it needs no callback to read. We use it for strings and numbers where equality is the question, and we switch to findLastIndex() the moment the question becomes a condition.

Where lastIndexOf() stops being the right tool

The method cannot take a predicate, cannot find NaN, and compares objects by reference. It also searches by scanning, so repeated lookups against a large array are slow compared with a Set or Map built once. When any of those limits bite, switch to findLastIndex() or a different structure.

The behavior is defined at Array.prototype.lastIndexOf in the ECMAScript specification, and documented on the MDN lastIndexOf page.

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.