In this tutorial, we will show you how to use the JavaScript array
indexOf()
andlastIndexOf()
methods to find the position of an element in an array.
indexOf()
methodTo find the position of an element in an array, you use the indexOf()
method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.
The following illustrates the syntax of the indexOf()
method.
Array.indexOf(searchElement, fromIndex)
As shown above, the indexOf()
method accepts two named arguments.
searchElement
argument is the element that you want to find in the array.fromIndex
is an array index at which the function starts the search.The fromIndex
argument can be a positive or negative integer. If the fromIndex
argument is negative, the indexOf()
method starts searching at array’s length plus fromIndex
.
In case you omit the fromIndex
argument, the indexOf()
method starts searching from the begining of the string.
Notice that the indexOf()
method uses the strict equality comparison algorithm that is similar to the triple-equals operator (===
) when comparing the searchElement
with the elements in the array.
indexOf()
method examplesSuppose, you have an array scores
that consists of six numbers as follows:
var scores = [10, 20, 30, 10, 40, 20];
The following example uses the indexOf()
method to find the elements in the scores
array:
console.log(scores.indexOf(10)); // 0
console.log(scores.indexOf(30)); // 2
console.log(scores.indexOf(50)); // -1
console.log(scores.indexOf(20)); // 1
#javascript #programming #developer #web-development