References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript array.indexOf() method

Method JavaScript All modern browsers Updated
Quick answer

The indexOf() method returns the first index where a value appears in an array, or -1 if it isn't there. ["a", "b", "c"].indexOf("b") is 1. When you only need a yes/no answer rather than the position, includes() is clearer.

Overview

indexOf() tells you where a value sits in an array. It returns the index of the first match, counting from 0, or -1 when the value isn't found. That -1 is the signal you check against — if (arr.indexOf(x) === -1) means "x is not in the array."

You can pass a second argument to start the search from a given index, which is useful for finding the next occurrence after a known one. It compares with strict equality (===), so types must match — ["1"].indexOf(1) is -1.

Since includes() arrived, indexOf() is mostly reserved for when you actually need the position — for example to remove an item with splice(). For a plain presence check, includes() reads better and, unlike indexOf(), can find NaN. To search from the end instead, there's lastIndexOf().

Syntax

const i = array.indexOf(searchElement)
const i = array.indexOf(searchElement, fromIndex)

Parameters

The array.indexOf() method accepts the following parameters.

Parameter Description
searchElement The value to locate, compared with strict equality (===).
fromIndex Optional. The index to start searching from. Negative counts back from the end.

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const colors = ['red', 'green', 'blue'];

  document.getElementById('out').textContent =
    "green is at index " + colors.indexOf('green') + '\n' +
    "pink is at index "  + colors.indexOf('pink');
  // green is at index 1 / pink is at index -1
</script>

Best practices

  • Check the result against -1 to test for "not found" — that's the sentinel value.
  • Use indexOf() when you need the position; for a yes/no check use includes().
  • Pair it with splice() to remove an item by value: find the index, then splice it out.
  • Remember the comparison is strict — indexOf won't match a number against a numeric string.

Frequently asked questions

What does indexOf() return if the value is not found?
-1. That's why you see checks like if (arr.indexOf(x) === -1) for "not present".
What is the difference between indexOf() and includes()?
indexOf() returns the position (or -1); includes() returns true/false. Use includes() for presence, indexOf() when you need the index.
How do I remove an item from an array by value?
Find it with indexOf(), then remove it with splice(): const i = arr.indexOf(x); if (i !== -1) arr.splice(i, 1);.
Why does indexOf() not find my value?
It uses strict equality, so types must match. A number won't equal its string form, and two different objects never match even if they look the same.