Q7: Implement a polyfill for Array.prototype.every().

Difficulty:BeginnerTopic:Array Methods

Answer

The every() method returns true if every existing element satisfies the callback condition. It returns false immediately when an element fails.

Array.prototype.myEvery = function (callback, thisArg) {
  if (this == null) {
    throw new TypeError("Array.prototype.myEvery 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++) {
    if (i in array && !callback.call(thisArg, array[i], i, array)) {
      return false;
    }
  }

  return true;
};

console.log([2, 4, 6].myEvery(n => n % 2 === 0));
// true

Explanation

every() is the logical counterpart of some(). It short-circuits on the first failing element. An empty array returns true, which is known as vacuous truth.

Key Takeaways
  • Every checks whether all existing elements satisfy a condition.
  • Every returns true for an empty array.