;

Javascript Array - indexOf() Method


Tutorialsrack 09/10/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.indexOf(). How does this method work in javascript? 

Array.prototype.indexOf()

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.

Syntax
array.indexOf(searchElement, fromIndex);

This method takes 2 parameters as given below:

  • searchElement: This parameter holds the element to search in the array.
  • fromIndex(Optional):  This parameter holds the position in this array at which to begin searching for 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:

Examples
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!


Related Posts



Comments

Recent Posts
Tags