indexOf()

ES5+

Returns the first index at which a given element can be found in the array.

Syntax

array.indexOf(searchElement, fromIndex)

Parameters

searchElement any

Element to locate in the array

Return Value

number

The index of the element, or -1 if not found

Examples

JavaScript
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.indexOf('banana'));
console.log(fruits.indexOf('mango'));
Output:
// 1 -1

📌 When to Use

Use indexOf() when you need the position of a primitive value in an array. It's useful for removing items, checking order, or when you need to work with the index value directly.

⚠️ Common Mistakes

Using if(indexOf(x)) instead of if(indexOf(x) !== -1) - index 0 is falsy!

indexOf() cannot find NaN - [NaN].indexOf(NaN) returns -1, use includes() or findIndex()

Expecting indexOf() to work with objects by value - it compares by reference

✅ Best Practices

Use includes() for simple existence checks when you don't need the index

Always compare with !== -1, not with > 0 (which misses index 0)

Use lastIndexOf() to find the last occurrence of a value

⚡ Performance Notes

indexOf() is O(n) and uses strict equality (===). For frequent lookups, convert the array to a Set or Map for O(1) access. The fromIndex parameter can improve performance by skipping already-searched portions.

🌍 Real World Example

Removing an Item from an Array

Find and remove a specific value from an array using indexOf and splice

const tags = ['javascript', 'typescript', 'react', 'vue'];

function removeTag(tagToRemove) {
  const index = tags.indexOf(tagToRemove);
  if (index !== -1) {
    tags.splice(index, 1);
    return true;
  }
  return false;
}

removeTag('vue');
console.log(tags); // ['javascript', 'typescript', 'react']

Related Methods