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
array.indexOf(searchElement, fromIndex?)Parameters
| Parameter | Type | Description |
|---|---|---|
| searchElement | T | Element to locate in the array |
| fromIndex | number | Zero-based index at which to start searching |
Return Value
The first index of the element, or -1 if not found
Examples
const animals = ['dog', 'cat', 'bird', 'cat'];
console.log(animals.indexOf('cat')); // 1const numbers = [2, 5, 9, 2];
console.log(numbers.indexOf(2)); // 0
console.log(numbers.indexOf(2, 1)); // 3const 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
Array.prototype.lastIndexOfReturns the last index at which a given element can be found in the array, or -1 if it is not present, searching backwards
Array.prototype.includesDetermines whether an array includes a certain value among its entries, returning true or false
Array.prototype.findIndexReturns the index of the first element in an array that satisfies the provided testing function
String.prototype.indexOfReturns the index of the first occurrence of a specified value in a string, or -1 if not found
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.