JavaScript is a dynamic programming language which can be used on both client side and server side. JavaScript is used to create interactive webpages. It has many frameworks such as React JS, Angular JS, Node JS etc. JavaScript provides some methods using which the index of the specified element can be obtained. indexOf and findIndex are those methods.
The indexOf Function in JavaScript
The indexOf function in JavaScript allows us to search for an element in an array and returns the first found index in that array. If it can’t find the element, then -1 is returned. The syntax of this method is given below:
array.indexOf(element, index)
Here, array is the list of elements on which indexOf method is performed. Element represents the element which is to be searched and index is the position from where it should start.
Example
Let’s consider an array of names of months. We’ll use the indexOf method to find the index of the month ‘Mar’
const months = ['Jan', 'Feb', 'Mar', 'April', 'May']
console.log (months.indexOf('Mar'))
Output
// 2
It gives the output index as “2”. If the search element is not present in the array, it returns “-1” as output.
Console.log (months.indexOf('Aug'))
As the element is not present in the array months, indexOf function returns “-1”.
The findIndex Function JavaScript
The array.findIndex() function of JavaScript is used to return the first found index of the element present in the array when it satisfies the condition that is specified in the function. The element is passed by the user during function call. If the element is not present the array, -1 is returned.
The syntax of findIndex method is given below:
arr.findIndex (func(element, index, arr), thisArg)
Here, “arr” represents the array on which the findIndex function is being performed.
findIndex method can be used in two ways, i.e., using the “return” keyword and using “inline” function. Here, as we are passing a function to another function, they are known as “callback functions”.
Using the “return” Keyword
Let’s consider we have an array of colors as red, green, blue, yellow, orange. We want the index of the color yellow.
Example
const colors = ['red', 'green', 'blue', 'yellow', 'orange']
function is_yellow (element) {
return element === 'yellow'
}
result = colors.findIndex(is_yellow)
console.log ("The index of 'yellow' is: " + result)
Output
// The index of 'yellow' is: 3
Conclusion
Both indexOf and findIndex methods return the first index of the element specified. indexOf method takes the element whose index is to be returned as the argument and findIndex takes a function as an argument. But both the functions return “-1” as output.