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:
callingArray.indexOf(valueToFind, startIndex);
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
["Sunday", "Tuesday", "Friday"].indexOf("Tuesday");
// The invocation above will return: 1
Example 2: Find the index of Sunday
["Sunday", "Tuesday", "Friday"].indexOf("Sunday");
// The invocation above will return: 0
Example 3: Find the index of 5
[1, 3, 5, 7].indexOf(5);
// The invocation above will return: 2
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
const daysOfWeek = [ "Sunday", "Tuesday", "Thursday", "Friday", "Tuesday", "Sunday", "Tuesday", "Friday",];
daysOfWeek.indexOf("Tuesday", 3);
// The invocation above will return: 4
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:
const daysOfWeek = [ "Sunday", "Tuesday", "Thursday", "Friday", "Tuesday", "Sunday", "Tuesday", "Friday",];
daysOfWeek.indexOf("Tuesday", -3);
// The invocation above will return: 6
Example 2: Find the index of Sunday
from the 1st index position
const daysOfWeek = [ "Sunday", "Tuesday", "Friday", "Sunday", "Tuesday", "Friday",];
daysOfWeek.indexOf("Sunday", 1);
// The invocation above will return: 3
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:
const daysOfWeek = [ "Sunday", "Tuesday", "Friday", "Sunday", "Tuesday", "Friday",];
daysOfWeek.indexOf("Sunday", 75);
// The invocation above will return: -1