Javascript Array indexOf() Method

In this article, we will discuss indexOf() method for Javascript array.

Javascript array indexOf():

  • It returns the index of the first occurrence of a specified element within the array.
  • Returns -1 if an element is not found.
  • The first element has index 0, the second element has index 1 and so on.

Syntax 1:

array.indexOf(element);

Example:


var array = ['b', 'c', 'd', 'c', 'b'];

console.log(array.indexOf('c'));
// output: 1

console.log(array.indexOf('e'));
// output: -1

Syntax 2:

array.indexOf(element, startFromIndex);

Example:


var array = ['b', 'c', 'd', 'c', 'b'];

// here we specify startFromIndex so it will start searching from index 1 (so 'b' at index 0 will be ignored)
console.log(array.indexOf('b', 1));
// output: 4

console.log(array.indexOf('c', 2));
// output: 3

Leave a Reply

avatar
  Subscribe  
Notify of