How to implement Array.prototype.lastIndexOf? JavaScript Interview Question | Problem Solving | JavaScript Polyfills
@Yomesh Gupta

Do you see value in our efforts?

Devtools Tech is a free platform for Frontend Engineers. It takes a lot of time, effort, and finanical resources to keep the platform running. If you see any value in our work and would like to support us then you can do using the following options.


In this question, the candidate needs to implement a function customLastIndexOf that mimics the behaviour of Array.prototype.lastIndexOf method.

More about Array.prototype.lastIndexOf

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex. -1 is returned.


const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

// expected output: 3

// expected output: 1

console.log(animals.lastIndexOf('Dodo', 2));
// expected output: 0


The customLastIndexOf takes two parameters

  1. searchElement

Element to locate in the array.

  1. fromIndex (Optional)

The position in the array at which to start searching backwards. Defaults to the array's length minus one (arr.length - 1), causing the whole array to be searched.

A fromIndex value greater than or equal to the length of the array also causes the whole array to be searched.

A fromIndex value greater than 0 is taken as the offset from the beginning of the array.

A fromIndex value less than 0 is taken as the offset from the end of the array — in other words, it is taken as specifying the position at array.length + fromIndex. Therefore, if array.length + fromIndex is less than 0, the array is not searched, and the method returns -1.

customLastIndexOf(searchElement, fromIndex?)


Start the timer, complete your solution, and test it against the test cases provided by the platform. Ideally, you should finish this question within 30 mins. Share your solution with us --

Loading IDE...