Find Index with indexOf()
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
Empty array returns -1
Single element at index 0
Returns first occurrence (index 1)
30 is at index 2
25 not found, returns -1
Algorithm Flow

Solution Approach
Best Answers
function solution(arr, val) {
return arr.indexOf(val);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
