Performance Characteristics of findLast()
You'll learn how findLast() compares to find() in terms of performance and when it can actually be faster.
Understanding O(n) Search
Like find(), findLast() has O(n) time complexity — in the worst case, it must examine every element in the array. Whether you search from the start or the end, you might need to check all n elements.
However, the key difference lies in short-circuiting behavior.
When findLast() Wins
Think of searching for a book in a library. If you're looking for something recently published and the shelves are sorted newest-to-oldest, starting from the front (end) saves you walking the entire building.
findLast() works backward, so if matching elements tend to be near the end of your array, it finds them faster:
const recentLogs = [
{ time: 100, error: false },
{ time: 200, error: false },
{ time: 300, error: false },
{ time: 400, error: true } // Near the end!
];
// findLast() checks only 1 element before finding it
const lastError = recentLogs.findLast(log => log.error);
// find() would check all 4 elements first
const firstError = recentLogs.find(log => log.error);
The Practical Advantage
The performance difference only matters when:
- Your arrays are large
- Matches cluster near the end
- You're calling it frequently in hot paths
For small arrays or evenly distributed matches, the difference is negligible.
Key Takeaway: findLast() has O(n) complexity like find(), but short-circuits earlier when target elements are near the array's end, making it faster for "search from the back" scenarios.