Code Logo

Find Index with indexOf()

Published at25 Jul 2026
JavaScript Collections Easy 0 views
Like0

Write a JavaScript function that takes an array and a value, and returns the first index where the value appears using Array.indexOf(), or -1 if the value is not present.

Array.prototype.indexOf() is a JavaScript method that returns the first index at which a given element can be found in the array. It uses strict equality (===) to compare elements. If the element is not present, it returns -1. An optional second parameter specifies the starting index for the search.

The indexOf() method is the standard way to check if an element exists in an array and find its position. The pattern arr.indexOf(val) !== -1 is the traditional way to check for existence before Array.includes() was introduced in ES6. It remains widely used for finding positions rather than just checking existence.

Time complexity is O(n) where n is the array length, as it performs a linear search. Space complexity is O(1). The search starts from index 0 and proceeds from left to right, stopping at the first match.

Edge cases include empty arrays (returns -1), NaN values (indexOf uses === which considers NaN !== NaN, so NaN is never found), multiple occurrences (returns the first one only), and searching for undefined or null values.

Example Input & Output

Example 1
Input
[],5
Output
-1
Explanation

Empty array returns -1

Example 2
Input
[42],42
Output
0
Explanation

Single element at index 0

Example 3
Input
[1,2,3,2,1],2
Output
1
Explanation

Returns first occurrence (index 1)

Example 4
Input
[10,20,30,40],30
Output
2
Explanation

30 is at index 2

Example 5
Input
[10,20,30],25
Output
-1
Explanation

25 not found, returns -1

Algorithm Flow

Recommendation Algorithm Flow for Find Index with indexOf()
Recommendation Algorithm Flow for Find Index with indexOf()

Solution Approach

function solution(arr, val) {
  return arr.indexOf(val);
}

Best Answers

javascript - Approach 1
function solution(arr, val) {
  return arr.indexOf(val);
}