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.
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; }; }
Check if findLastIndex exists: The if (!Array.prototype.findLastIndex) ensures that the polyfill is only applied if findLastIndex doesn't already exist on Array.prototype.
Callback validation: It checks if the callback is a valid function using typeof 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.
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)
-1 is returned.-1 right away.-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