How to implement Array indexOf from scratch? | 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, you need to build an exact replica of the indexOf method provided by Array.

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


indexOf(searchElement, fromIndex)


searchElement - Element to locate in the array.

fromIndex (Optional) - The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the provided index is 0, then the whole array will be searched. Default: 0 (entire array is searched).

Return value

The first index of the element in the array; -1 if not found.


indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).


var array = [2, 9, 9];
array.indexOf(2);     // 0
array.indexOf(7);     // -1
array.indexOf(9, 2);  // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0

Loading IDE...