DEV Community

Discussion on: "for" vs. "forEach" and the value of documentation

Collapse
 
qm3ster profile image
Mihail Malo • Edited

I think it's helpful to understand why, regardless of what the forEach method actually does, the above couldn't work.
Even if we imagine that forEach short circuits on a truthy return value from the function passed in... and returns that value...
There's still no way that value would make it to the output of our greaterThan function.

const array1 = [2,3,4,5];
function equalOrGreaterThan(numbr){
    return array1.forEach(function(item){
        if (item >= numbr){
            return true;
        };
    })
    || false;
};

This would work (if that's what forEach did), since we are taking note of the return value. (The || false is there so that we know exactly what we're returning, not null or undefined)

Since the .findIndex() .find() .some() family of methods do exist, we can indeed do that:

const array1 = [2,3,4,5]
function equalOrGreaterThan(numbr){
    return array1.some(function(item){
        return item >= numbr
    })
}

Functions that have only one statement - a return statement, are also prime candidates to be arrow functions:

const array1 = [2,3,4,5]
const equalOrGreaterThan👌 = numbr =>
    array1.some(item => item >= numbr)
Collapse
 
qm3ster profile image
Mihail Malo

Finally, if doing this in real life, you probably want to avoid iterating on every check if the array is unchanged:

const equalOrGreaterThan👌 = array => {
    const max = Math.max(...array)
    return numbr => max >= numbr
}
const equalOrGreaterThan👌😂 = array => {
    let max = Math.max(...array)
    return {
        isIt: number => max >= numbr
        push: (...args) => { max = Math.max(max, ...args)}
    }
}