🔙 Array.prototype.findLast() Polyfill
Category: js / polyfills
Difficulty: medium
The findLast() method returns the last element in an array that satisfies a given predicate function. It iterates from the end of the array. ✅ Implementation [code example] Explanation: Check if findLast is defined: The if (!Array.prototype.findLast) condition ensures that the polyfill only runs if findLast is not already available. Callback validation: It checks whether the callback provided is a valid function using typeof callback !== 'function'. Iterate backward: The loop starts from the last element of the array (i = this.length - 1) and moves towards the first element (i--). Calling the callback: callback.call(thisArg, this[i], i, this) is used to invoke the callback function. This gives you the correct value for this within the callback function, the current element (this[i]), its index (i), and the array itself (this). Return the matching element: If the callback returns a truthy value, that element is returned as the result of findLast. Return undefined if no match is found: If the loop completes without finding a match, undefined is returned. Example Usage: [code example] In this example, findLast finds the last even number (4) in the array. Edge Cases: If no element matches the condition, it returns undefined. If the array is empty, it returns undefined. This implementation closely mimics the behavior of the modern findLast method that was introduced in newer versions of JavaScript. <!-- quiz-start --> Q1: What does [1, 2, 3, 4, 5].findLast(num => num % 2 === 0) return? [ ] 2 [x] 4 [ ] [2, 4] [ ] 3 Q2: How does findLast() differ from find()? [ ] findLast() returns all matching elements [ ] findLast() is slower [x] findLast() iterates from the end of the array [ ] findLast() returns the index instead of the element Q3: What does findLast() return when no element matches? [ ] -1 [ ] null [ ] The last element of the array [x] undefined <!-- quiz-end -->...