The JavaScript Array indexOf() Method is used to find the index of the first occurrence of the search element provided as the argument to the method. This method always compares the search element to the element present in the array using strict equality. Therefore, when the search element is NaN then it returns -1 because NaN values are never compared as equal.
Syntax:
array.indexOf(element, start)
Parameters: This method accepts two parameters as mentioned above and described below:
- 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.
Example 1: Below is an example of the Array indexOf() method.
javascript
let name = [ 'gfg' , 'cse' , 'geeks' , 'portal' ];
a = name.indexOf( 'gfg' )
console.log(a)
|
Example 2: In this example, the method will be searched for element 2 in that array and return that element index.
javascript
let A = [1, 2, 3, 4, 5];
a = A.indexOf(2)
console.log(a);
|
Example 3: In this example, the method will be searched for element 9 in that array if not found then return -1.
javascript
let name = [ 'gfg' , 'cse' , 'geeks' , 'portal' ];
a = name.indexOf( 'cat' )
console.log(a);
|
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.
Supported Browsers: The browsers supported by JavaScript Array indexOf() method are listed below:
- 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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
07 Jul, 2023
Like Article
Save Article