📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Syntax
arr.indexOf(searchElement[, fromIndex])
- search - Element to locate in the array.
- fromIndex (Optional) - The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched.
Examples
Example 1: Simple Array indexOf() method example
var progLangs = ['C', 'C++', 'Java', 'PHP', 'Python'];
console.log(progLangs.indexOf('C'));
// start from index 2
console.log(progLangs.indexOf('PHP', 2));
console.log(progLangs.indexOf('Python'));
0
3
4
Example 2: Locate values in an array using indexOf() method
var array = [2, 9, 9];
console.log(array.indexOf(2));
console.log(array.indexOf(7));
console.log(array.indexOf(9, 2));
console.log(array.indexOf(2, -1));
console.log(array.indexOf(2, -3));
0
-1
2
-1
0
Example 3: Finding all the occurrences of an element
var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}
console.log(indices);
[0, 2, 4]
Comments
Post a Comment
Leave Comment