Categories
JavaScript JavaScript Basics

How to Use the Array indexOf Method in JavaScript

Spread the love

The JavaScript array’s indexOf method returns the index of the first instance of a given entry when starting the search from the beginning of the array. Otherwise -1 is returned.

It takes up to 2 arguments. The first is the item to search for. The 2nd argument is an optional argument with the array index to start searching from.

The search is done by comparing the entry by using the === operator, which does comparison without type coercion beforehand.

For instance, we can use it as follows:

const index = [1,2,3].indexOf(2);

In the code above, we called indexOf on the array [1,2,3] with argument 2. This should return 1 and assign that to index since the first instance of 2 appears as the 2nd entry of the array.

We can also pass in an index number to the 2nd argument. For instance, we can write the following:

const index = [1, 2, 3].indexOf(2, 2);

index should be -1 in this case since we specified that we start searching from index 2 and beyond. 2 doesn’t exist in index 2 or beyond so -1 is returned.

Conclusion

indexOf lets search for an item in the array with either starting from the beginning or from a starting index.

It uses the === operator to compare each entry to find a match.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.