Javascript - Array indexOf() Method

The indexOf() method searches the array for the specified item, and returns its position.

Description

The indexOf() method searches the array for the specified item, and returns its position.

The search starts at the specified position, or at the beginning if no start position is specified.

It returns -1 if the item is not found.

If the item is present more than once, the indexOf method returns the position of the first occurrence.

The first item has position 0.

To search from end to start, use the lastIndexOf() method

Syntax

array.indexOf(item,start)

Parameter Values

Parameter Require Description
item Required. The item to search for
start Optional. Where to start the search. Negative values will start at the given position counting from the end, and search to the end.

Return

A Number, representing the position of the specified item, otherwise -1

Example

Search an array for the item "Database":

Demo

var myArray = ["XML", "Json", "Database", "Mango"];
var a = myArray.indexOf("Database");
console.log( a);/*from   w  ww  .jav  a2  s.c o  m*/

//Search an array for the item "Database", starting the search at position 4:

var myArray = ["XML", "Json", "Database", "Mango", "XML", "Json", "Database", "Mango"];
var a = myArray.indexOf("Database", 4);
console.log( a );

//at position of -5
var myArray = ["XML", "Json", "Database", "Mango", "XML", "Json", "Database", "Mango"];
var a = myArray.indexOf("Database", -5);
console.log( a );

Result