How to write JavaScript some and every method from scratch

Basic implementation of JS some and every method.

·

1 min read

How to write JavaScript some and every method from scratch

some

Returns true if at least the callback function returns true otherwise false.

Array.prototype._some = function(cbFunction) {
    for(let i = 0; i < this.length; i++) {
        if(cbFunction(this[i], i, this)) {
            return true
        }
    }

    return false
}

const numbers = [1, 2, 3, 4, 5, 6, 7, 8];

console.log(numbers._some((item) => item % 2 === 0));

// Output
// true
  • runs the callback function for each element and passes item, index and array.

  • if any of the calls returns true then return true otherwise false.

every

Returns true if every item in the array returns true on calling the callback function otherwise false.

Array.prototype._every = function(cbFunction) {
    for(let i = 0; i < this.length; i++) {
        if(!cbFunction(this[i], i, this)) {
            return false
        }
    }

    return true
}

const numbers = [1, 2, 3, 4, 5, 6, 7, 8];

console.log(numbers._every((item) => item % 2 === 0));

// Output
// false
  • if even one time if our callback function returns false it going to return false otherwise true.