Loading article...
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.
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
customFind method iterates through the array using a for loop.callbackFn with the current element, its index, and the array.thisArg : If provided, thisArg is used to bind this inside the callback function using .call(thisArg, this[i], i, this).callbackFn, it returns undefined.customFind(element => element > 10) returns the first element greater than 10, which is 12.customFind(element => element > 200), it returns undefined..call(thisArg, ...)?this Binding : The .call(thisArg, ...) ensures that the this value inside the callback is explicitly set to thisArg. This is crucial when thisArg is provided and the callback relies on it.
Without .call(), the this value could be undefined (in strict mode) or the global object (non-strict mode), leading to unexpected results. By using .call(thisArg, ...), we guarantee that thisArg is used as the context inside the callback..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' }
.call(thisArg, ...) allows explicit control over the this context inside the callback..call(), the this context inside the callback may not behave as expected, especially when thisArg is provided.Test your understanding with 3 quick questions