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:
searchElement
: The element to search for in the array.fromIndex
(optional): The index at which to begin the search. The default is0
. 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)
Example 2: Searching with a starting index
Example 3: Element not found
Example 4: Searching for a string with case sensitivity
Example 5: Using fromIndex
to search backwards
Example 6: Searching with negative fromIndex
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.