.indexOf()

The .indexOf() method returns the first index at which an element can be found. Returns -1 if the element is not found.

Syntax

array.indexOf(searchElement, startIndex);
  • searchElement: The element we are looking for.
  • startIndex: The index position to begin search from. Optional.

A negative startIndex will offset from the end of the array to begin search.

Examples

In the example below, the index for the number 12 is logged to the console:

const numbers = [6, 12, 8, 10];
const indexOf12 = numbers.indexOf(12);
console.log(indexOf12);
// Output: 1

If element is not found the result will be -1:

const pizzaToppings = ['pepperoni', 'olives', 'mushrooms'];
const indexOfPineapple = pizzaToppings.indexOf('pineapple');
console.log(indexOfPineapple);
// Output: -1

Check if color 'blue' is in the colors array and after the first element:

const colors = ['blue', 'orange', 'pink', 'yellow', 'teal'];
const checkBlue = colors.indexOf('blue', 1);
console.log(checkBlue);
// Output: -1

Codebyte Example

Multiple matches will only return the first index where a match occurs:

Code
Output
Loading...

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn JavaScript on Codecademy