Implement Array.indexOf

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Implement Array.indexOf

Approach

Linear scan from fromIndex using strict equality to find the first matching element. Handle negative fromIndex by computing the offset from the end. Return the index on the first match, or -1 if the value is not found in the remaining elements.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Array Polyfill

Why It Works

IndexOf returns the numeric position of the first occurrence, enabling operations like removing duplicates, finding positions for splice, or checking existence before includes was introduced.

Updated Feb 2026