This site runs best with JavaScript enabled.

indexOf

Kevin Beck

August 14, 2019


The indexOf() method returns the first index at which a givien element can be found in an array, or it returns -1 if it is not present.

var beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
console.log(beasts.indexOf('giraffe'));
// expected output: -1

You can also use the fromIndex prameter to set the start of the search. (Default: 0)

var beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

Syntax:

arr.indexOf(searchElement[, fromIndex])

Source