Q8: Implement a polyfill for Array.prototype.find().

Difficulty:BeginnerTopic:Array Methods

Answer

The find() method returns the first array element for which the callback returns a truthy value. If no element matches, it returns undefined.

Unlike map(), filter(), and forEach(), find() invokes the callback for every index below the captured length, including holes in sparse arrays. A hole is read as undefined.

Array.prototype.myFind = function (callback, thisArg) {
  if (this == null) {
    throw new TypeError("Array.prototype.myFind called on null or undefined");
  }

  if (typeof callback !== "function") {
    throw new TypeError("Callback must be a function");
  }

  const array = Object(this);
  const length = array.length >>> 0;

  for (let i = 0; i < length; i++) {
    const value = array[i];

    if (callback.call(thisArg, value, i, array)) {
      return value;
    }
  }

  return undefined;
};

console.log([5, 12, 8, 130].myFind(n => n > 10));
// 12

Explanation

The loop stops immediately when a matching element is found. Returning from the function avoids unnecessary callback executions.

Key Takeaways
  • Find returns the first matching value, not an array.
  • Unlike several other array iteration methods, find visits sparse-array indexes as undefined.