JavaScript Array.indexOf() Method
We use the array.indexOf()
method to find the first occurrence of the element in the reference array. Then, it is used to find the occurrence of the element
in the given array.
Syntax
let values = ["Delft","Stack","Netherlands"];
let index = values.indexOf("element");
index = values.indexOf("element","startIndex");
Parameters
element |
The array.indexOf method finds the index of the first occurrence of the element in an array. |
startIndex |
It starts finding the element in the array from the startIndex . If we pass the negative startIndex , it searches in the last startIndex number of indexes. |
Returns
The Array.indexOf()
returns -1
if the element is not found in the array; otherwise, it returns an index of the first occurrence of the element
in the array.
Example Codes
Let’s learn the uses of the Array.indexOf()
method by going through different code examples below.
Use Array.indexOf()
to Find the Element in an Array
When we don’t pass the startIndex
parameter to the Array.indexOf()
method, it starts searching for the element
from the 0th
index.
The following code takes two different examples and finds the first occurrence of the element
using the Array.indexOf()
method. The output for the following code shows that for value Nether
, the method returns the -1
as it is not in the array.
let values = ["Delft","Stack","Netherlands"];
let index1 = values.indexOf("Delft");
let index2 = values.indexOf("Nether");
console.log(index1)
console.log(index2);
Output:
0
-1
Use Array.indexOf()
With Positive & Negative startIndex
When we add the positive startIndex
, the method starts searching for the element
from the startIndex
and searches till the last index of the array. When the user passes the negative startIndex
to array.indexOf()
, it searches in the last startIndex
number of elements from front to end.
For example, the following code fence has an array of length 5
, and we have passed the -2
as a startIndex
, so the method will search for the last 2
elements from the front to back.
let array = ["10.2","30","43.2","21","0"];
let index1 = array.indexOf("10.2",2);
let index2 = array.indexOf("21",-2);
console.log(index1)
console.log(index2);
Output:
-1
3
The Array.indexOf()
method compares the element
using the strict equality (===
) operator, which means it also compares the element
type. Furthermore, it performs the case-sensitive comparison for the string values.