🔙 Array.prototype.findLastIndex() Polyfill
Category: js / polyfills
Difficulty: medium
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 [code example] Explanation: 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. Example Usage: [code example] Edge Cases: No elements match: If no elements satisfy the condition, -1 is returned. Empty array: If the array is empty, it returns -1 right 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. <!-- quiz-start --> Q1: What does [1, 2, 3, 4, 5].findLastIndex(num => num % 2 === 0) return? [ ] 1 [x] 3 [ ] 4 [ ] [1, 3] Q2: What is the starting point for iteration in findLastIndex()? [ ] Index 0 [ ] The middle of the array [x] The last index (length - 1) [ ] A random index Q3: What does findLastIndex() return for an empty array? [x] -1 [ ] undefined [ ] 0 [ ] null <!-- quiz-end -->...