Array

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

JavaScript
array.lastIndexOf(searchElement, fromIndex?)

Parameters

ParameterTypeDescription
searchElementTElement to locate in the array
fromIndexnumberZero-based index at which to start searching backwards

Return Value

The last index of the element, or -1 if not found

Examples

Basic Usage
const animals = ['dog', 'cat', 'bird', 'cat'];
console.log(animals.lastIndexOf('cat')); // 3
Practical Example
const numbers = [2, 5, 9, 2];
console.log(numbers.lastIndexOf(2)); // 3
Advanced Usage
const arr = [1, 2, 3, 1, 2];
console.log(arr.lastIndexOf(2, 2)); // 1

Understanding 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

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.