JavaScript Array indexOf() Tutorial

In this section, we will learn what the indexOf() method is and how to use it in JavaScript.

JavaScript Arrays indexOf() Method

The `indexOf()` method is used to find the index number of an element in the target Array object.

Array indexOf() Syntax:

array.indexOf(item, start)

Array indexOf() Method Parameters:

The method takes two arguments:

  • The first argument is the element that we want to know its index number.
  • The second argument is the position from which the search should start.

Note: by default, the execution engine starts from the index 0 of the target array.

Array indexOf() Method Return Value:

If the element is in fact in the target array, the return value of the method will be the index number of that element. But if the element doesn’t exist in the target array, the return value of the method will be -1.

Note: if the element that we set as the argument exists in multiple positions of the target array, the returned index number will be of the first occurrence.

Example: using Array indexOf() method in JavaScript

const arr = ["Apple","Google","Microsoft"];




Example: JavaScript search in array for index

const obj1 = {
   name: "John", 
   age: 1000
const obj2 = {
   name: "Omid",
   age: 29
const obj3 = {
   name : "Jack", 
   age :52
const arr = [obj1,obj2,obj3];
console.log (arr.indexOf(obj2));



Top Technologies