Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.indexOf

Finds a value in an array and returns its index.

Available since: ES5

Syntax

array.indexOf(searchElement, fromIndex)

Parameters

ParameterTypeDescription
searchElementanyThe value to find.
fromIndexnumberOptional. The position to start searching from. From the beginning by default.

Return value

numberThe index of the first match, or -1.

Examples

The position of an element:

const colors = ['red', 'green', 'blue'];
 
console.log(colors.indexOf('green'));
console.log(colors.indexOf('pink'));

Output:

1
-1

Removing an element by value:

const colors = ['red', 'green', 'blue'];
const index = colors.indexOf('green');
 
if (index !== -1) {
  colors.splice(index, 1);
}
 
console.log(colors.join(', '));

Output:

red, blue

Notes

The comparison is strict, like ===, so [NaN].indexOf(NaN) gives -1 and objects are found only by reference. To find an object by a property use findIndex().

See also

Related recipes

In the tutorial

  • Searching arrays — How to find an element in a JavaScript array: includes, indexOf, find, findIndex, some and every.

Thanks for reading!

Donate to the site — we work hard for you.