JavaScript Array indexOf() Method
The indexOf()
method in JavaScript is used to find the index of the first occurrence of a specified element in an array.
Syntax
array.indexOf(element, start)
Parameters:
- element: This parameter holds the element whose index will be returned.
- start: This parameter is optional and it holds the starting point of the array, where to begin the search the default value is 0.
Return value: This method returns the index of the first occurrence of the element. If the element cannot be found in the array, then this method returns -1.
JavaScript Array indexOf() Method Examples
Example 1: Finding Index of Element in Array
This code demonstrates the use of the indexOf()
method to find the index of the element “gfg” in the array name
. The index of “gfg” is stored in the variable a
and then logged to the console.
JavaScript
let name = ['gfg', 'cse', 'geeks', 'portal'];
a = name.indexOf('gfg')
// Printing result of method
console.log(a)
Example 2: Searching Element in Array
This code demonstrates the use of the indexOf()
method to find the index of a specific element (2
) in an array (A
). It returns the index of the first occurrence of the element in the array (1
in this case). If the element is not found, it returns -1
.
JavaScript
// Taking input as an array A
// having some elements.
let A = [1, 2, 3, 4, 5];
// indexOf() method is called to
// test whether the searching element
// is present in given array or not.
a = A.indexOf(2)
// Printing result of method.
console.log(a);
Output:
1
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.
Supported Browsers:
- Google Chrome 1 and above
- Edge 12 and above
- Firefox 1.5 and above
- Internet Explorer 9 and above
- Opera 9.5 and above
- Safari 3 and above
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.
Last Updated :
14 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...