JavaScript indexOf()
The indexOf()
method in JavaScript is used to search for a specified value in an array or string. It returns the index of the first occurrence of the specified value, or -1 if the value is not found.
Syntax
array.indexOf(searchValue, fromIndex)
string.indexOf(searchValue, fromIndex)
Parameters:
searchValue
: The value to search for in the array or string.fromIndex
(optional): The index to start the search from. If not specified,fromIndex
defaults to 0 for both arrays and strings.
Example
const array = [2, 4, 6, 8, 10];
console.log(array.indexOf(6)); // Output: 2
const string = 'Hello, world!';
console.log(string.indexOf('world')); // Output: 7
Output
The output of the above code will be:
2
7