JavaScript(JS) array method - indexof

htt‮/:sp‬/www.theitroad.com

The indexOf() method is an array method in JavaScript that returns the index of the first occurrence of a specified value in an array. If the value is not found, it returns -1.

Here's the syntax of the indexOf() method:

array.indexOf(searchValue[, fromIndex]);
  • array is the array that the indexOf() method is called on.
  • searchValue is the value to search for in the array.
  • fromIndex is the index to start searching from. It is an optional parameter, and if not specified, the search starts from index 0.

The indexOf() method returns the index of the first occurrence of the specified value in the array, or -1 if the value is not found.

Here's an example of how to use the indexOf() method:

let array = [1, 2, 3, 4, 5];

console.log(array.indexOf(3)); // 2
console.log(array.indexOf(6)); // -1

In this example, we have an array array containing the elements [1, 2, 3, 4, 5]. We use the indexOf() method to find the index of the first occurrence of the value 3 and 6. The output of this code will be:

2
-1

Note that the indexOf() method is case sensitive. If you want to perform a case-insensitive search, you can convert the elements in the array to lowercase (or uppercase) before calling the indexOf() method.