0
0
JavascriptHow-ToBeginner · 3 min read

How to Find Index of Element in Array in JavaScript

To find the index of an element in a JavaScript array, use the indexOf() method. It returns the first index where the element is found or -1 if the element is not present.
📐

Syntax

The indexOf() method is called on an array and takes one required argument: the element to find. It returns the index of the first matching element or -1 if not found.

  • array.indexOf(searchElement)
  • searchElement: The element you want to find in the array.
javascript
array.indexOf(searchElement)
💻

Example

This example shows how to find the index of the number 3 in an array. It also shows what happens when the element is not found.

javascript
const numbers = [1, 2, 3, 4, 5];

const indexFound = numbers.indexOf(3);
console.log(indexFound); // 2

const indexNotFound = numbers.indexOf(10);
console.log(indexNotFound); // -1
Output
2 -1
⚠️

Common Pitfalls

One common mistake is expecting indexOf() to work with complex objects or arrays inside arrays. It only works with primitive values like numbers and strings by comparing with strict equality.

Also, indexOf() returns -1 if the element is not found, so always check for this before using the index.

javascript
const arr = [{id: 1}, {id: 2}];

// This will not find the object because objects are compared by reference
console.log(arr.indexOf({id: 1})); // -1

// Correct way: find index by a property
const index = arr.findIndex(obj => obj.id === 1);
console.log(index); // 0
Output
-1 0
📊

Quick Reference

Remember these points when using indexOf():

  • Returns the first index of the element found.
  • Returns -1 if element is not in the array.
  • Works with primitive types (numbers, strings, booleans).
  • Use findIndex() for objects or complex conditions.

Key Takeaways

Use indexOf() to find the position of a primitive element in an array.
indexOf() returns -1 if the element is not found.
For objects or complex searches, use findIndex() instead.
Always check the returned index before using it to avoid errors.