The every() method tests whether all elements in the array pass the test implemented by the provided function.
✅ Implementation
Array.prototype.customEvery = function (callback, thisArg) { if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } for (let i = 0; i < this.length; i++) { if (!callback.call(thisArg, this[i], i, this)) { return false; // Return false immediately if one element fails } } return true; // Return true if all elements pass the test }; // Example usage: const input = [2, 4, 6, 8]; const isEven = (element) => element % 2 === 0; console.log(input.customEvery(isEven)); // Output: true console.log([2, 4, 5, 8].customEvery(isEven)); // Output: false console.log([].customEvery(isEven)); // Output: true (empty array always returns true)
How It Works
- Checks if
callbackis a function- If not, throws a
TypeError(same behavior asArray.prototype.every).
- If not, throws a
- Iterates through the array
- Calls
callbackfor each element with(element, index, array). - Uses
.call(thisArg, ...)to bindthisArgif provided.
- Calls
- Returns early if any test fails
- If
callbackreturnsfalsefor any element,customEveryimmediately returnsfalse(optimized).
- If
- Returns
trueif all tests pass- If all elements satisfy the condition, it returns
true.
- If all elements satisfy the condition, it returns
Edge Cases Handled
✔ Empty array always returns true
✔ Stops checking as soon as one element fails (Optimized)
✔ Works with thisArg binding
✔ Throws an error if callback is not a function
This implementation is efficient, clean, and mirrors Array.prototype.every exactly.
Quick Quiz
Test your understanding with 3 quick questions
Q1What does `[].customEvery(x => x > 0)` return?
Q2When does `every()` return `false`?
Q3What happens if the callback is not a function?