In JavaScript, the indexOf() method is useful for finding the first index of a specific element within an array. If the element cannot be found, then it will return -1. Here is the basic syntax
array.indexOf(element, fromIndex)element represents the value you want to search for within the array, and the fromIndex parameter is the position from which the search should start. The fromIndex parameter is optional. If fromIndex is not provided, the search starts from the beginning of the array. Let’s look at an example
let fruits = ["apple", "banana", "orange", "banana"];
let index = fruits.indexOf("banana");
console.log(index); // 1In this example, we have an array fruits containing various fruit names. We use the indexOf() method to find the index of the string banana within the fruits array. Since banana is present at index 1, the method returns 1, which is stored in the index variable and logged to the console.
If the element you’re searching for is not found in the array, indexOf() returns -1. For example
let fruits = ["apple", "banana", "orange"];
let index = fruits.indexOf("grape");
console.log(index); // -1Here, we search for the string grape in the fruits array using indexOf(). Since grape is not present in the array, the method returns -1, which is stored in the index variable and logged to the console.
If you want to start looking for an item after a specific index number, then you can pass a second argument like in this example
let colors = ["red", "green", "blue", "yellow", "green"];
let index = colors.indexOf("green", 3);
console.log(index); // 4In this example, the search does not start from the start of an array, rather it starts from the index number 3 which is yellow and gets the output of 4.