offline version v3


95 of 264 menu

indexOf method

The indexOf method searches for an element in an array. In the first parameter, specify the element text. The method returns the number of the first found element, or -1 if there is no such element. The second optional parameter of the method specifies the position from which to start searching.

Syntax

array.indexOf(element, [where to start]);

Example

Let's find the position of the first three in the array:

let arr = [1, 2, 3, 3, 3, 4, 5]; let res = arr.indexOf(3); console.log(res);

The code execution result:

2

Example

Let now the element being checked is not in the array:

let arr = [1, 2, 3, 4, 5]; let res = arr.indexOf(6); console.log(res);

The code execution result:

-1

Example

Let's start the search from a given position:

let arr = [1, 2, 3, 4, 5, 3]; let res = arr.indexOf(3, 4); console.log(res);

The code execution result:

5

Frequent mistake

Sometimes the method is used to check if an element is in an array. In this case, it is easy to make a mistake if you check as follows:

if (arr.indexOf(3)) { console.log(true); } else { console.log(false); }

Such a check will work for all positions, except for zero - after all, it is interpreted as false.

Properly check for the presence of an element as follows:

if (arr.indexOf(3) !== -1) { console.log(true); } else { console.log(false); }

See also

  • the includes method
    that checks for the presence of an element in an array
  • the lastIndexOf method
    that searches for elements from the end
  • the at method
    that returns an array element by its index
  • the match method
    that searches for matches in a string
  • the search method
    that performs search
enru