JavaScript Array indexOf()

Last Updated On Saturday 9th Apr 2022

Java Script Array indexOf()

In this tutorial, we will learn about the JavaScript Array indexOf() method with the help of examples.

The indexOf() method returns the first index of occurance of an array element, or -1 if it is not found.

Syntax

	arr.indexOf(searchValue, fromIndex)
	
  • Here arr is an Array

Parameters

  • searchValue ( required ) – The element to locate in the array.
  • fromIndex (optional) – The index to start the search at. By default, it is .

Return Value

  • A Number – The first position where the search-value occurs.
  • Returns -1 if the element is not found in the array.

indexOf() method uses the strict equality comparison algorithm (similar to the triple-equals operator or ===) compares searchValue

Using indexOf() method example

	const countries = ["UK", "USA", "Germany", "Spain"];
console.log(countries.indexOf("USA"));
console.log(countries.indexOf("Spain"));
	

OutPut

	1
3
	

No Occurrence is Found

	const countries = ["UK", "USA", "Germany", "Spain"];
// if not found , returns -1
console.log(countries.indexOf("Italy"));
	

Output

	-1
	

Suppose, you have an array marks that consists of six numbers

	const marks = [ 11, 22, 33, 44, 55, 66 ];
	

The indexOf() method to find the elements in the marks array

	console.log(marks.indexOf(11)); // 0
console.log(marks.indexOf(44)); // 3
console.log(marks.indexOf(66)); // 5
console.log(marks.indexOf(33)); // 2
console.log(marks.indexOf(22)); // 1
console.log(marks.indexOf(55)); // 4
	

Case Sensitive

The indexOf() is case-sensitive. Lets See the example

	const countries = ["UK", "USA", "Germany", "Spain"];
// case-senstive
console.log(countries.indexOf("usa")); // -1
	

To Overcome , You can convert string in an array to lowercase before using the indexOf() method.

	const countries = ["UK", "USA", "Germany", "Spain"];
// Convert Each Item to LowerCase
const sameCaseCountries = countries.map((e) => e.toLowerCase());
console.log(sameCaseCountries.indexOf("usa".toLowerCase()));
console.log(sameCaseCountries.indexOf("SpAin".toLowerCase()));
	

Output

	1
3
	

References