In JavaScript, all data is stored in variables whose size depends on the selected data type. Only one value can be stored in bool, and numeric variables have certain limits of memory provided. The maximum possible size of variables such as string or array allows storing large volumes of the same type of data, from one word to fragments or even a whole poem.

JavaScript has built-in methods for working with such data. One of them is indexOf(), which allows you to determine the order of the selected fragment in the total amount of data.

To use this method, it is necessary to set a pattern of the desired element with any length. It will return back the index where the first character of the desired element is located - this allows us to perform checks for the presence and use other built-in methods to change the string in parts.

Another feature of the indexOf() method is that it is equivalently available for String and Array objects, but, in the case with array, it will return the index of the cell where the desired value was found.

How does indexOf() work?

IndexOf() reads the selected source from the first to the last value, without modifying the source data. This method can take 2 parameters: fragmentValue and startIndex.

The fragmentValue parameter is required because it specifies a sample for what it should look in the string or array. The startIndex parameter is optional and allows you to select the index from which search will be started.

indexOf(fragmentValue, startIndex);

If you specify a positive number in startIndex, the search starts from the left (or less) part of the original data. If you use a negative number, it will be carried out in the opposite direction, but still started from 0. Moreover, if the startIndex value exceeds the maximum possible index for source content, then it will return "-1".

It should be noted that to get the correct result of method execution, the assignment of the initial data (string or array) must be performed before method declaration. So use it only for sources with correct data types and content.

The behaviour of the method depends on the success / failure of finding selected value. If the method finds it, then the index of its first mention will be returned to the user as a positive number, if not - it will return the "-1" too.

IndexOf() looks for a fragment that completely matches with fragmentValue, so it is case sensitive and must exactly match its intended counterpart in the source data.

Also it should be mentioned that IndexOf() stops searching after the first detection of the desired fragmentValue. To find the indices of all possible references, you must use the method in combination with loops or its multiple calls.

IndexOf() for strings syntax

For correct method execution, the value of the original string variable must be assigned. As fragmentValue, you can specify a specific value or use the variable to which it was assigned. It is worth noting that indexOf() converts any data passed to fragmentValue to string.

An example of using indexOf() for String:

let text = 'My random text.';
let result = text.indexOf('text');
console.log(result);

Result

10

Together with the optional startIndex parameter:

let text = 'My random text.';
let result = text.indexOf('text', 11);
console.log(result);

Result

-1

In the second example, we got -1, which means that the method didn't find the desired fragmentValue. This happened because we started reading at the 11th character of the line, while its mention starts at the 10th character.

IndexOf() for arrays syntax

The indexOf() syntax for arrays is the same as for strings. The original array must be declared previously, as well as its values. The search will be carried out by its values and, if successful, will return the index of the array cell.

let animals = ['wolf', 'bear', 'cow', 'cat', 'dog'];
let result = animals.indexOf('cat');
console.log(result);

Result

3

With a negative optional startIndex parameter:

let animals = ["wolf", "cat", "cow", "bear", "dog"];
let test = "cat";
console.log(animals.indexOf(test, -4));

Result

1

Here startIndex was a negative number, so indexOf() began to read the array from element with zero index and then from higher index to a lower one. It is easy to check the correctness of the result if you calculate the indices of the array elements yourself, starting with 'dog' and moving towards the desired 'cat' value.

Test yourself

  • Task 1. Find the indices for numbers from 1 to 5 in the given numeric array and print them to the console.

let numbers = [7, 66, 19, 83, 81, 43, 77, 81, 32, 57, 54, 47, 84, 84, 66, 3];

Solution

In this array there are no duplicate values, so we can solve it by initiating indexOf()for each of the 5 required numbers. To optimize the code, we will also place it inside the console.log() method.

let numbers = [7, 66, 19, 8, 81, 43, 7, 1, 32, 57, 54, 47, 84, 66, 3];
console.log(numbers.indexOf(1));
console.log(numbers.indexOf(2));
console.log(numbers.indexOf(3));
console.log(numbers.indexOf(4));
console.log(numbers.indexOf(5));

Result

7
-1
14
-1
-1

From the requested numbers only 2 and 3 were found, while checks for others return -1.

  • Task 2. Print the indices of the array elements to the console using indexOf() when startIndex is: 0, 1, -1.

let geoArray = ['continent', 'ocean', 'island'];

Solution

Let's put the indexOf() method inside console.log() to optimize the length of our code. Then, for each array element, we implement using indexOf with startIndex = 0. After that, we repeat the written lines changing startIndex to 1 and -1, respectively.

let geoArray = ['continent', 'ocean', 'island'];
console.log(geoArray.indexOf('continent', 0));
console.log(geoArray.indexOf('ocean', 0));
console.log(geoArray.indexOf('island', 0));
console.log(geoArray.indexOf('continent', 1));
console.log(geoArray.indexOf('ocean', 1));
console.log(geoArray.indexOf('island', 1));
console.log(geoArray.indexOf('continent', -1));
console.log(geoArray.indexOf('ocean', -1));
console.log(geoArray.indexOf('island', -1));

Result

0
1
2
-1
1
2
-1
-1
2

The result shows how changing the start point of reading (startIndex) in indexOf affects the indices detection.

  • Task 3. Find the indexes of all occurrences of the word "white"" in the text.

let text = 'If trees are white, and roofs are white, then it is snowing outside.';

Solution

This task can be accomplished by manually calculating the indices of all characters, but in practice you may meet large chunks of text where such tasks will require a huge amount of time. Alternative way is to automate the counting process using the indexOf() method.

let text = 'If trees are white, and roofs are white, then it is snowing outside.';
firstWordAppearing = text.indexOf('white');
secondWordAppearing = text.indexOf('white', firstWordAppearing +1);
console.log (firstWordAppearing);
console.log (secondWordAppearing);

Result

13
34

Having the index of the first word mentioned in the firstWordAppearing, we used it as an additional parameter when determining the second word. After adding 1 to its value, we started reading by the indexOf() from the point next after the first character, and since it searches only for complete matches, the next found value was the second mention of the searched word.