indexOf() and lastIndexOf() for Finding Elements
You'll learn how to search for specific elements in an array and get their positions.
The Core Idea
JavaScript arrays have two methods for finding where an element is located: indexOf() searches from the beginning to the end, while lastIndexOf() searches from the end to the beginning. Both return the index position of the element you're looking for, or -1 if it's not found.
Think of it like searching for a word in a book. indexOf() is like reading from page 1 forward until you find it, while lastIndexOf() is like starting at the last page and working backward.
How They Work
const fruits = ['apple', 'banana', 'orange', 'banana', 'grape'];
// Find the first occurrence
const firstBanana = fruits.indexOf('banana');
console.log(firstBanana); // 1
// Find the last occurrence
const lastBanana = fruits.lastIndexOf('banana');
console.log(lastBanana); // 3
// Element not found
const notFound = fruits.indexOf('mango');
console.log(notFound); // -1
Both methods use strict equality (===) for comparison, so they won't find similar but different values:
const numbers = [1, 2, 3, 4];
console.log(numbers.indexOf('2')); // -1 (string vs number)
console.log(numbers.indexOf(2)); // 1 (exact match)
You can also provide a second parameter to start searching from a specific index:
const letters = ['a', 'b', 'c', 'a', 'b', 'c'];
// Start searching from index 2
console.log(letters.indexOf('a', 2)); // 3
console.log(letters.lastIndexOf('b', 3)); // 1
Key Takeaway: Use indexOf() to find the first occurrence of an element and lastIndexOf() to find the last occurrence; both return the index position or -1 if the element isn't found.