indexOf() JavaScript Array Method – How to Get Text Index
Whenever you use indexOf() on an array, the method does the following:
- It searches its calling array for the method’s first argument.
- It returns the index of the first match, or
-1
if the method found no match.
Syntax of the indexOf()
Method
indexOf()
accepts two arguments. Here is the syntax:
Argument 1: valueToFind
A valueToFind
is the first argument accepted by the indexOf()
method. It defines the value you wish to find in the calling array.
Example 1: Find the index of Tuesday
Example 2: Find the index of Sunday
Example 3: Find the index of 5
Argument 2: startIndex
The startIndex
argument is optional. It specifies the index position where you want the computer to start searching for the valueToFind
argument.
Example 1: Find the index of Tuesday
from the 3rd index position
Suppose you specify a negative startIndex
argument. In that case, the computer will start the index count from the calling array’s last element.
Here’s an example:
Use beautiful images to learn CSS Flexbox.
Find out moreExample 2: Find the index of Sunday
from the 1st index position
Suppose the startIndex
argument is greater than or equal to the calling array’s length. In such a case, the computer will ignore the search.
Here’s an example: