The indexOf() method in JavaScript is used to find the first occurrence of a specified element in an array. It returns the index of the element, or -1 if the element is not found. This method is useful for searching for an element within an array and determining its position.
Syntax
array.indexOf(searchElement, fromIndex);
Parameters
Parameters | Descriptions |
---|---|
searchElement | The element to search for in the array. |
fromIndex (Optional) | The index at which to start searching for the element. If omitted, the search starts from index 0. |
Return Value
Return Type | Description |
---|---|
Number | The index of the first occurrence of the element, or -1 if the element is not found. |
Example 1: Using indexOf() to Find an Element
This code demonstrates how to use the indexOf() method to find the index of a specific element in an array.
let numbers = [1, 2, 3, 4, 5]; console.log(numbers.indexOf(3)); // Output: 2 (index of number 3) console.log(numbers.indexOf(6)); // Output: -1 (6 is not in the array)
Example 2: Using indexOf() with fromIndex
You can specify the fromIndex parameter to start the search from a specific index.
let numbers = [1, 2, 3, 4, 5, 3, 6]; // Output: 5 (index of first occurrence of 3 starting from index 3) console.log(numbers.indexOf(3, 3));
Example 3: Using indexOf() to Check for NaN
The indexOf() method can be used to check for the presence of NaN in an array.
let array = [1, 2, NaN, 4, 5]; console.log(array.indexOf(NaN)); // Output: 2 (index of NaN)
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1.5 | 9.5 | 3 |