In this article, you will learn about the javascript Array built-in method Array.prototype.indexOf()
. How does this method work in javascript?
This Array.prototype.indexOf()
method returns the first index at which a given element can be found in the array, otherwise, it returns -1
if the element is not present in an array.
array.indexOf(searchElement, fromIndex);
This method takes 2 parameters as given below:
searchElement
. If the index is greater than or equal to the array's length, then it returns -1
, which means the array will not be searched. The indexOf()
method skips empty slots in sparse arrays.
Here are some examples of Array.prototype.indexOf() method:
const array = [2, 9, 9, 3, 8, 6, 5, 10];
console.log(array.indexOf(2));
// Output => 0
console.log(array.indexOf(7));
// Output => -1
console.log(array.indexOf(9, 2));
// Output => 2
console.log(array.indexOf(2, -1));
// Output => -1
console.log(array.indexOf(2, -3));
// Output => -1
//Using indexOf() on sparse arrays
console.log([1, , 3, 5].indexOf(undefined));
// Output => -1
I hope this article will help you to understand the javascript Array built-in method Array.prototype.indexOf().
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments