In this tutorial, we will show you how to use the JavaScript array indexOf() and lastIndexOf() methods to find the position of an element in an array.

Introduction to the JavaScript array indexOf() method

To 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.

  1. The searchElement argument is the element that you want to find in the array.
  2. The 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.

The JavaScript array indexOf() method examples

Suppose, 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

JavaScript Array Tutorial - Locating an Element in an Array
1.60 GEEK