The indexOf() method returns the first index at which the element can be found in the array, or -1 if the element is not present. This method is case sensitive for string element.
const arr = [10, 20, 30, 40, 50];
console.log(arr.indexOf(10)); // Output: 0
console.log(arr.indexOf(30)); // Output: 2
console.log(arr.indexOf(50)); // Output: 4
Syntax
indexOf(searchElement) // or
indexOf(searchElement, fromIndex)
Parameters
Parameters | Descriptions |
---|---|
searchElement | The element whose index is to be find. |
fromIndex (Optional) | Its default value is 0, which means search the element from beginning of the array. If fromIndex is greater than or equal to the array’s length, the method returns -1 as no search is performed. If fromIndex is negative, then the index counts back from the end of the array. if -array.length <= fromIndex < 0, fromIndex + array.length is used. |
Return Value
It returns the first index of searchElement in the array, or -1 if the element is not found.
Example 1: Basic example of array indexOf() method.
const arr = ["apple", "banana", "cherry", "apple"];
console.log(arr.indexOf("apple")); // Output: 0
console.log(arr.indexOf("cherry")); // Output: 2
console.log(arr.indexOf("mango")); // Output: -1
Example 2: The indexOf() method with two parameters.
const arr = [10, 20, 30, 40, 50];
console.log(arr.indexOf(40, 2)); // Output: 3
console.log(arr.indexOf(10, 1)); // Output: -1
Example 3: Set the fromIndex value to Negative.
const arr = [10, 20, 30, 40, 50];
console.log(arr.indexOf(50, -1)); // Output: 3 (starts search at the last element)
console.log(arr.indexOf(40, -3)); // Output: 1 (starts search at index 1)
Example 4: Case Sensitivity
const arr = ["Apple", "banana", "Cherry"];
console.log(arr.indexOf("apple")); // Output: -1
console.log(arr.indexOf("Apple")); // Output: 0