Array

Array.prototype.indexOf

Returns the first index at which a given element can be found in the array, or -1 if it is not present

Syntax

JavaScript
array.indexOf(searchElement, fromIndex?)

Parameters

ParameterTypeDescription
searchElementTElement to locate in the array
fromIndexnumberZero-based index at which to start searching

Return Value

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

Examples

Basic Usage
const animals = ['dog', 'cat', 'bird', 'cat'];
console.log(animals.indexOf('cat')); // 1
Practical Example
const numbers = [2, 5, 9, 2];
console.log(numbers.indexOf(2)); // 0
console.log(numbers.indexOf(2, 1)); // 3
Advanced Usage
const arr = [1, 2, 3];
if (arr.indexOf(4) === -1) {
  console.log('4 not found');
}

Understanding Array.prototype.indexOf

The Array.prototype.indexOf method in JavaScript returns the first index at which a given element can be found in the array, or -1 if it is not present. It belongs to the Array object and is one of the most widely used methods for working with array values in modern JavaScript and TypeScript applications.

The method signature is array.indexOf(searchElement, fromIndex?). It accepts 2 parameters: searchElement, fromIndex. When called, it returns the first index of the element, or -1 if not found. Understanding when and how to use indexOf() helps you write more expressive, readable code.

Common use cases for Array.prototype.indexOf include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like array-lastindexof, array-includes, array-findindex, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for Array.prototype.indexOf is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More Array Methods

Other methods in the Array object

Related Tools

More Array Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.