The indexOf() method returns the first index of occurance of an array element, or -1 if it is not found.
Example
indexOf() Syntax
The syntax of the indexOf() method is:
arr.indexOf(searchElement, fromIndex)
Here, arr is an array.
indexOf() Parameters
The indexOf() method takes in:
- searchElement - The element to locate in the array.
- fromIndex (optional) - The index to start the search at. By default, it is 0.
indexOf() Return Value
- Returns the first index of the element in the array if it is present at least once.
- Returns -1 if the element is not found in the array.
Note: indexOf() compares searchElement to elements of the Array using strict equality (similar to triple-equals operator or ===).
Example 1: Using indexOf() method
Output
3 0 4 -1
Notes:
- If fromIndex >= array.length, array is not searched and -1 is returned.
- If fromIndex < 0, the index is calculated backward. For example, -1 denotes the last element's index and so on.
Example 2: Finding All the Occurrences of an Element
Output
[ 0, 4, 7 ] [ 1 ] []
Example 3: Finding If Element exists else Adding the Element
Output
Element not Found! Updated the array. [ 'Monitor', 'Keyboard', 'Mouse', 'Speaker', 'CPU' ] Mouse is already in the array.
Recommended Reading: JavaScript Array.lastIndexOf()