The find() method returns the first element in an array that satisfies a provided testing function. If no element matches, it returns undefined. This polyfill supports the optional thisArg parameter for binding context.
β Implementation
Array.prototype.customFind = function(callbackFn, thisArg) { // Iterate through the array and execute the callback function for (let i = 0; i < this.length; i++) { // Call the callback function with the current element, index, and array // .call() is used to explicitly set 'this' inside the callback if (callbackFn.call(thisArg, this[i], i, this)) { return this[i]; // Return the first matching element } } return undefined; // Return undefined if no element matches }; // Example usage: const array = [5, 12, 8, 130, 44]; // Using customFind to find the first element greater than 10 const found = array.customFind(element => element > 10); console.log(found); // Output: 12
How It Works:
- Iteration : The
customFindmethod iterates through the array using aforloop. - Callback Execution : For each element, it calls the provided
callbackFnwith the current element, its index, and the array.
- If the callback returns a truthy value, the method immediately returns that element.
- Optional
thisArg: If provided,thisArgis used to bindthisinside the callback function using.call(thisArg, this[i], i, this). - No Match : If no element satisfies the condition in
callbackFn, it returnsundefined.
Example:
customFind(element => element > 10)returns the first element greater than 10, which is12.- If no element matches, such as
customFind(element => element > 200), it returnsundefined.
Why Use .call(thisArg, ...)?
- Explicit
thisBinding : The.call(thisArg, ...)ensures that thethisvalue inside the callback is explicitly set tothisArg. This is crucial whenthisArgis provided and the callback relies on it. Without.call(), thethisvalue could be undefined (in strict mode) or the global object (non-strict mode), leading to unexpected results. By using.call(thisArg, ...), we guarantee thatthisArgis used as the context inside the callback.
Example of .call() in Action:
function printThis() { console.log(this); // Logs the value of `this` } const obj = { name: 'Alice' }; // Using `.call()` to set `this` to `obj` printThis.call(obj); // Logs: { name: 'Alice' }
Summary:
.call(thisArg, ...)allows explicit control over thethiscontext inside the callback.- Without
.call(), thethiscontext inside the callback may not behave as expected, especially whenthisArgis provided.
Quick Quiz
Test your understanding with 3 quick questions
Q1What does `[5, 12, 8, 130].customFind(x => x > 10)` return?
Q2What does `find()` return when no element matches?
Q3Why is `.call(thisArg, ...)` used in the find polyfill?