The indexOf()
method in JavaScript is used to search an array for a specified element, and returns the index of the first occurrence of the element in the array. If the element is not found in the array, the indexOf()
method returns -1
.
Here is an example of how the indexOf()
method works:
const array1 = [1, 2, 3, 4, 5];
const result = array1.indexOf(3);
// the result will be: 2
In the code example above, we first declare an array called array1
that contains the numbers 1
through 5
. We then use the indexOf()
method to search the array1
array for the number 3
. The indexOf()
method takes a single argument, which is the element to search for in the array. In this case, we search for the number 3
.
As a result of calling the indexOf()
method, the result
variable will be set to 2
, which is the index of the first occurrence of the number 3
in the array1
array. If the element we were searching for was not found in the array, the result
variable would be set to -1
.
Leave a Reply