The indexOf() method of the Array class in JavaScript returns the first (least) index at which a given element can be found in the calling array. If the element is not found, it returns -1.
There are 2 variations for the syntax of Array.indexOf() method. They are:
indexOf(searchElement)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchElement | required | The element to locate in the array. |
This method returns the first (least) index at which a given element can be found in the calling array, starting the search at the beginning of the array.
Returns value of type Number
.
indexOf(searchElement, fromIndex)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchElement | required | The element to locate in the array. |
fromIndex | optional | The index to start the search at. Defaults to 0. |
This method returns the first (least) index at which a given element can be found in the calling array, starting the search at the specified fromIndex.
Returns value of type Number
.
In JavaScript, we can use the indexOf() method to find the index of a specified element in an array.
For example,
const arr = [1, 2, 3, 4, 5];
const indexOfThree = arr.indexOf(3);
console.log(indexOfThree);
2
We can use the indexOf() method to find the index of a specified element in an array, starting the search from a specific index.
For example,
const arr = [1, 2, 3, 4, 5, 3];
const indexOfThreeFromIndex3 = arr.indexOf(3, 3);
console.log(indexOfThreeFromIndex3);
5
We can use the indexOf() method to find the index of a specified string in an array.
For example,
const strArr = ['apple', 'banana', 'cherry'];
const indexOfBanana = strArr.indexOf('banana');
console.log(indexOfBanana);
1
In this JavaScript tutorial, we learned about indexOf() method of Array: the syntax and few working examples with output and detailed explanation for each example.