I was wondering what people think about using a reduce function vs loop for
returning true if a condition exists.
Example:
var a = [1, 5, 7, 4, 2, 5, 3];
var greaterThan5 = a.reduce(function(prev, val) {
return (prev || val > 5);
}, false);
vs
var greaterThan5 = false;
for(var i = 0; i < a.length; i++) {
if(a[i] > 5) {
greaterThan5 = true;
break;
}
}
vs
var i = 0;
var greaterThan5 = false;
while(!greaterThan5 && i < a.length) {
greaterThan5 = (a[i] > 5);
i++;
}
The for
loop and while
loop will exit when the condition is true, but I think the reduce syntax is easier to read and gives less room for run-time errors.