JavaScript Array indexOf() method


The indexOf() method in JavaScript is used to determine the index of the first occurrence of a specified element in an array. If the element is not found, it returns -1. This method is case-sensitive and can be particularly useful for searching through arrays.

Syntax:

let index = array.indexOf(searchElement, fromIndex);
  • searchElement: The element to search for in the array.
  • fromIndex (optional): The index at which to begin the search. The default is 0. If the specified index is greater than or equal to the array's length, the search starts from the end of the array.

Return Value:

  • The index of the first occurrence of the specified element within the array, or -1 if the element is not found.

Key Points:

  • Case-sensitive: The search is case-sensitive for string elements.
  • Returns the first index: If the element appears multiple times in the array, indexOf() will return the index of the first occurrence.
  • Starts searching from a specified index: You can start searching from a specific index using the fromIndex parameter.

Example 1: Basic usage (Finding a number)

let numbers = [10, 20, 30, 40, 50]; let index = numbers.indexOf(30); // Find the index of 30 console.log(index); // 2

Example 2: Searching with a starting index

let numbers = [10, 20, 30, 20, 50]; let index = numbers.indexOf(20, 2); // Start searching from index 2 console.log(index); // 3 (the second occurrence of 20)

Example 3: Element not found

let fruits = ['apple', 'banana', 'orange']; let index = fruits.indexOf('grape'); // Look for an element that does not exist console.log(index); // -1

Example 4: Searching for a string with case sensitivity

let words = ['hello', 'world', 'Hello']; let index1 = words.indexOf('hello'); // Check for lowercase 'hello' let index2 = words.indexOf('Hello'); // Check for uppercase 'Hello' console.log(index1); // 0 console.log(index2); // 2

Example 5: Using fromIndex to search backwards

let numbers = [1, 2, 3, 4, 5, 3]; let index = numbers.indexOf(3, 4); // Start searching from index 4 console.log(index); // 5 (the second occurrence of 3)

Example 6: Searching with negative fromIndex

let numbers = [10, 20, 30, 40, 50]; let index = numbers.indexOf(20, -3); // Start searching from the 3rd last index console.log(index); // 1

Summary:

  • The indexOf() method is a straightforward way to search for an element in an array and retrieve its index.
  • It returns the index of the first occurrence of the specified element, or -1 if the element is not present, making it a useful tool for searching operations within arrays.
  • The optional fromIndex parameter allows for customized searching, including starting from a specific point or searching backwards.