DEV Community

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

Collapse
 
joelnet profile image
JavaScript Joel

If we break down the code, it is easier to see what is going on.

I'm gonna pull the function out of the forEach and create a new gte function.

function gte(a, b){
  if (a >= b){
    return true;
  };
  return false;
};

function greaterThan(numbr){
    array1.forEach(item => gte(numbr, item));
//                 ------------------------
//               /
// Now it's easier to see that this doesn't do anything.
    return false;
};

Array.forEach's first argument is a function. I would recommend always breaking the function out to make the code more understandable.

When written this way, it is more clear what is going on and that you would not expect the forEach to return a value from the outer function greaterThan.

I also agree with kip, the better way would be some or every since it will break early on a false and not iterate the entire array.

array1 = [2,3,4,5];
const greaterThan = numbr => array1.some(item => item >= numbr);

greaterThan(4); //=> true
greaterThan(9); //=> false
greaterThan(2); //=> true
greaterThan(1); //=> true
Collapse
 
aritdeveloper profile image
Arit Developer

Thank you so much for this!