Mastering the lastIndexOf() Method in JavaScript
Introduction
The lastIndexOf() method in JavaScript is used to find the last occurrence of a specified value within a string or an array. It searches from right to left but still returns the index relative to the start of the string or array. 🧠
📌 What is lastIndexOf()?
While indexOf() finds the first match, lastIndexOf() finds the last one. It's also case-sensitive for strings and uses strict equality (===) for arrays.
- 🔍 Works on both strings and arrays.
- 📜 Returns the index of the last occurrence.
- ❌ Returns -1 if no match is found.
- 🔄 Search starts from the end, but indexes are still counted from the start.
💡 Syntax
Basic Syntax
// For strings
string.lastIndexOf(searchValue, fromIndex)
// For arrays
array.lastIndexOf(searchElement, fromIndex)Parameters:
- searchValue / searchElement — The value to search for.
- fromIndex — Optional position to start searching backwards (default is the last index).
🧵 Example with Strings
String lastIndexOf()
const text = "Hello World Hello";
console.log(text.lastIndexOf("Hello")); // 12
console.log(text.lastIndexOf("o")); // 16
console.log(text.lastIndexOf("x")); // -1📦 Example with Arrays
Array lastIndexOf()
const fruits = ["Apple", "Banana", "Mango", "Banana"];
console.log(fruits.lastIndexOf("Banana")); // 3
console.log(fruits.lastIndexOf("Orange")); // -1➡️ Using fromIndex Parameter
Using fromIndex
const numbers = [1, 2, 3, 2, 4];
console.log(numbers.lastIndexOf(2)); // 3
console.log(numbers.lastIndexOf(2, 2)); // 1⚠️ Important Notes
Note
For strings, lastIndexOf() is case-sensitive, so "Hello".lastIndexOf("h") will return -1. For arrays, it uses strict equality, so ["2"].lastIndexOf(2) returns -1.
📊 Quick Reference Table
| Type | Example | Result |
|---|---|---|
| String | "Hello Hello".lastIndexOf("Hello") | 6 |
| Array | [1, 2, 3, 2].lastIndexOf(2) | 3 |
| Not Found | [1, 2, 3].lastIndexOf(4) | -1 |
>>"lastIndexOf() is like a reverse detective — it starts from the end but still reports the position from the beginning." 🔍
🔥 Summary
The lastIndexOf() method is perfect when you need to locate the last occurrence of a value in strings or arrays. Remember that it’s case-sensitive for strings and strictly compares types for arrays.