JavaScript Array indexOf() Method
The indexOf() method in JavaScript is used to find the position of the first occurrence of a specific value in an array. If the value is not present, it returns -1. This method is handy for quickly determining where a particular item is located within 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 holds the starting point of the array, where the default value is 0 to begin the search.
Return value:
- The method returns the index of the first occurrence of the specified element.
- If the element is not found, it returns -1.
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 into the console.
let name = ['gfg', 'cse', 'geeks', 'portal'];
a = name.indexOf('gfg')
// Printing result of method
console.log(a)
Output
0
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
.
// 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:
JavaScript Array indexOf() Method- FAQs
How does the indexOf() method work?
The indexOf() method scans the array from the beginning to find the specified element, using strict equality (===) to compare values. It returns the index of the first match or -1 if not found.
How does indexOf() handle NaN values?
Since indexOf() uses strict equality, it cannot find NaN. This is because NaN is not considered equal to itself.
What happens if the fromIndex is out of bounds?
If fromIndex is greater than or equal to the array length, indexOf() returns -1. If fromIndex is negative, it is treated as array.length + fromIndex.
How does the performance of indexOf() compare to findIndex()?
The indexOf() method only looks for the exact match of an element, while findIndex() can locate an element based on a condition specified by a function.
What are some common use cases for the indexOf() method?
Common use cases for the
indexOf()
method include:
- Finding the position of a specific element in an array.
- Checking if an element exists in an array by comparing the returned index to
-1
.- Implementing functionality that requires knowing the first occurrence of an element.