Array.prototype.lastIndexOf
Returns the last index at which a given element can be found in the array, or -1 if it is not present, searching backwards
Syntax
array.lastIndexOf(searchElement, fromIndex?)Parameters
| Parameter | Type | Description |
|---|---|---|
| searchElement | T | Element to locate in the array |
| fromIndex | number | Zero-based index at which to start searching backwards |
Return Value
The last index of the element, or -1 if not found
Examples
const animals = ['dog', 'cat', 'bird', 'cat'];
console.log(animals.lastIndexOf('cat')); // 3const numbers = [2, 5, 9, 2];
console.log(numbers.lastIndexOf(2)); // 3const arr = [1, 2, 3, 1, 2];
console.log(arr.lastIndexOf(2, 2)); // 1Understanding Array.prototype.lastIndexOf
The Array.prototype.lastIndexOf method in JavaScript returns the last index at which a given element can be found in the array, or -1 if it is not present, searching backwards. It belongs to the Array object and is one of the most widely used methods for working with array values in modern JavaScript and TypeScript applications.
The method signature is array.lastIndexOf(searchElement, fromIndex?). It accepts 2 parameters: searchElement, fromIndex. When called, it returns the last index of the element, or -1 if not found. Understanding when and how to use lastIndexOf() helps you write more expressive, readable code.
Common use cases for Array.prototype.lastIndexOf include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like array-indexof, array-includes, array-findlastindex, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Array.prototype.lastIndexOf is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Array.prototype.indexOfReturns the first index at which a given element can be found in the array, or -1 if it is not present
Array.prototype.includesDetermines whether an array includes a certain value among its entries, returning true or false
Array.prototype.findLastIndexIterates the array in reverse order and returns the index of the first element that satisfies the provided testing function
More Array Methods
Other methods in the Array object
Related Tools
More Array Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.