Last Updated : 27 Sep, 2024
The indexOf() method in JavaScript is used to find the position of the first occurrence of a specific value in an array. If the value is not present, it returns -1. This method is handy for quickly determining where a particular item is located within an array.
Syntax:array.indexOf(element, start)Parameters:
This code demonstrates the use of the indexOf()
method to find the index of the element "gfg" in the array name
. The index of "gfg" is stored in the variable a
and then logged into the console.
let name = ['gfg', 'cse', 'geeks', 'portal'];
a = name.indexOf('gfg')
// Printing result of method
console.log(a)
Example 2: Searching Element in Array
This code demonstrates the use of the indexOf()
method to find the index of a specific element (2
) in an array (A
). It returns the index of the first occurrence of the element in the array (1
in this case). If the element is not found, it returns -1
.
// Taking input as an array A
// having some elements.
let A = [1, 2, 3, 4, 5];
// indexOf() method is called to
// test whether the searching element
// is present in given array or not.
a = A.indexOf(2)
// Printing result of method.
console.log(a);
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.
Supported Browsers:RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4