The findLastIndex() method returns the index of the last element that satisfies the provided testing function, iterating from end to start. Returns -1 if none found.
β Implementation
if (!Array.prototype.findLastIndex) { Array.prototype.findLastIndex = function(callback, thisArg) { // Ensure callback is a function if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } // Iterate backward through the array for (let i = this.length - 1; i >= 0; i--) { // If the element satisfies the condition, return the index if (callback.call(thisArg, this[i], i, this)) { return i; } } // Return -1 if no matching element is found return -1; }; }
Explanation:
-
Check if
findLastIndexexists: Theif (!Array.prototype.findLastIndex)ensures that the polyfill is only applied iffindLastIndexdoesn't already exist onArray.prototype. -
Callback validation: It checks if the
callbackis a valid function usingtypeof callback !== 'function'. -
Backward iteration: We iterate from the last element (
i = this.length - 1) to the first (i--). -
Callback invocation:
callback.call(thisArg, this[i], i, this)calls the provided callback for each element, passing the current element (this[i]), its index (i), and the array itself (this). -
Return index: If the callback returns a truthy value, we return the current index (
i). -
Return
-1: If no element matches the condition, we return-1, which indicates no match was found.
Example Usage:
const arr = [1, 2, 3, 4, 5]; const index = arr.findLastIndex(num => num % 2 === 0); console.log(index); // Output: 3 (because the last even number is 4 at index 3)
Edge Cases:
- No elements match: If no elements satisfy the condition,
-1is returned. - Empty array: If the array is empty, it returns
-1right away. - Callback that always returns false: If the callback always returns false, the result will be
-1.
This polyfill ensures the behavior of findLastIndex is available even in environments where it's not supported natively.
Test your understanding with 3 quick questions