The indexOf method in JavaScript serves the purpose of locating the position of the element that is passed as an argument to the function.
- It is important to note that the indexOf method differentiates between uppercase and lowercase letters.
Syntax:
Example
Array.indexof(value, start)
Parameters:
Value : Value to be search in the index.
Start: The initial value is set to 0. This indicates the position from which the search will commence.
Return value:
It provides the index of the element being searched for. If the specified element is not present within the array, this method will return -1.
Browser Support:
| Chrome | Yes |
|---|---|
Edge |
Yes |
| Firefox | Yes |
| Opera | Yes |
Example 1
JavaScript TypedArray indexOf Method
Example
<script type="text/javascript">
// JavaScript to illustrate indexOf() method
function pyVisualizer() {
var array = [2,3,5,4,6,7,8,9,12];
document.write(array.indexOf(6, 5));
}
runExample();
// expected output: arr[Output:-1]
</script>
Output:
Example 2
JavaScript TypedArray indexOf Method
Example
<script type="text/javascript">
// JavaScript to illustrate indexOf() method
function pyVisualizer() {
var array = [2,3,5,4,6,7,8,9,12];
document.write(array.indexOf(6, 2));
}
runExample();
// expected output: arr[Output:4]
</script>
Output: