References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript array.findLastIndex() method

Method JavaScript All modern browsers Updated
Quick answer

The findLastIndex() method returns the index of the last element that passes your test, searching from the end of the array, or -1 if none match. It's the position-returning partner of findLast(), and the from-the-end version of findIndex().

Overview

findLastIndex() searches an array from the end backward and returns the position of the first match it finds that way — the index of the last matching element in order. If nothing matches, it returns -1, the standard not-found sentinel.

It completes a neat grid of four search-by-condition methods: find() and findIndex() work from the start (returning the element and its index), while findLast() and findLastIndex() work from the end. Reach for the index version (rather than the element) when you need to act at that position — update, remove with splice(), or slice around it.

It saves you from the old workaround of reversing the array and adjusting the index by hand. The callback gets the usual element, index and array arguments. Support is solid in current browsers.

Syntax

const i = array.findLastIndex(callbackFn)

[1, 8, 3, 9, 2].findLastIndex(n => n < 5)  // 4 (the index of 2)

Parameters

The array.findLastIndex() method accepts the following parameters.

Parameter Description
callbackFn Test run on elements from the end backward until one returns truthy. Receives (element, index, array).
thisArg Optional. A value to use as this inside the callback.

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const log = ['ok', 'error', 'ok', 'error', 'ok'];

  const lastError = log.findLastIndex(entry => entry === 'error');

  document.getElementById('out').textContent =
    'last error at index ' + lastError; // 3
</script>

Best practices

  • Use it to get the position of the last element meeting a condition, without reversing.
  • Check the result against -1 for "not found".
  • Use findLast() when you need the element itself, not its index.
  • For matching from the start, use findIndex().

Frequently asked questions

What does findLastIndex() return?
The index of the last element that passes the test (searching from the end), or -1 if none match.
What is the difference between findLast() and findLastIndex()?
findLast() returns the matching element; findLastIndex() returns its index.
What is the difference between findIndex() and findLastIndex()?
findIndex() searches from the start; findLastIndex() searches from the end.
Is findLastIndex() widely supported?
Yes, in all current browsers. For older ones, reverse a copy and adjust the index from findIndex().