JavaScript array indexOf() function “returns the first index at which the given item can be found in an array or -1 if it is not present”. It searches the Array for a specified item and returns its position to the calling function.
Syntax
array.indexOf(element, start)
Parameters
- element: The item parameter is required, and its element, which we are searching inside an array.
- start: The start parameter is optional. It is the position where to start the search.
Return Value
The array indexOf() function returns the integer, the index of an element in the Array.
Example 1: How to use an array.indexOf() function
let pieces = ['king', 'queen', 'rook', 'knight', 'bishop'];
console.log(pieces.indexOf('rook'));
Output
Example 2: Finding all the occurrences of an element
Finding an element’s occurrences in a specific ray is a mon task in web development. Let us take a use case where we need to see all the events of the particular item.
let indices = [];
let array = ['a', 'b', 'a', 'c', 'a', 'd'];
let element = 'a';
let ids = array.indexOf(element);
while (ids != -1) {
indices.push(ids);
ids = array.indexOf(element, ids + 1);
}
console.log(indices);
In the above example, we search for one item until the whole Array is not searched.
Then, if the item’s position is found, it will be inside an array and, finally, log that Array.
Example 3: How to get an indexof objects in an array
To get an index of an array that contains objects, you can use the “map()” method. See the following code example in which we will find the index of a mike, which is 0 basically because when we add the two objects in the Array, st is the first object, meaning its index is 0.
let st = {
mike: 'Finn',
el: 'Millie'
};
let got = {
jon: 'Kit',
khaleesi: 'Emilia'
}
let arr = [];
arr.push(st, got);
pos = arr.map(function(e) { return e.mike; }).indexOf('Finn');
console.log(pos);
Output
0
Example 4: An array indexof() method is case insensitive.
To search an element in the array regardless of its case sensitivity, use the “array findIndex()” and “toLowerCase()” methods.
let arr = ['miLLie', 'fiNN', 'saDiE', 'caLEB', 'gaTEn'];
query = 'caleb',
pos = arr.findIndex(item => query.toLowerCase() === item.toLowerCase());
console.log(result);
Output
3
Browser Compatibility
- Google Chrome 1 and above
- Edge 12 and above
- Firefox 1.5 and above
- Internet Explorer 9 and above
- Opera 9.5 and above
- Safari 3 and above
Recommended Posts
JavaScript array lastIndexOf()

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.