The indexOf method in JavaScript arrays serves the purpose of locating the index of a specific element within an array. It is important to note that this method is case-sensitive.
In an array, the index of the initial element consistently begins at zero. If a specified element cannot be found within the array, the function returns -1.
Syntax
The syntax for the indexOf method is outlined as follows:
array.indexOf(element,index)
Parameter
element - This denotes the specific element that is to be located.
Return
An index of a particular element.
JavaScript Array indexOf method example
Let’s explore a few straightforward examples of the indexOf method.
Example 1
Here, we will print the position of an element.
<script>
var arr=["C","C++","Python","C++","Java"];
var result= arr.indexOf("C++");
document.writeln(result);
</script>
Output:
Example 2
In this instance, we will specify the index position from which the search will commence.
<script>
var arr=["C","C++","Python","C++","Java"];
var result= arr.indexOf("C++",2);
document.writeln(result);
</script>
Output:
Example 3
In this section, we will conduct a search for an element that does not exist within an array.
<script>
var arr=["C","C++","Python","C++","Java"];
var result= arr.indexOf("JavaScript");
document.writeln(result);
</script>
Output: