Write a function that returns the smallest number that’s greater or equal to 0. Especially that return right underneath if (num < 0). What's that return's job here?
function minNonNegative(numArray) {
let min = Infinity;
numArray.forEach(function(num) {
if (num < 0) {
return;
} else if (num < min) {
min = num
}
});
return min;
}
console.log(minNonNegative([-3,2,5,-9]))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
The return INSIDE the forEach is to ignore the else which is then not even needed:
numArray.forEach(num => { if (num < 0) return; if (num < min) { min = num } });
You can use a filter and Math.min:
const minNonNegative = numArray => Math.min(...numArray.filter(num => num>=0))
console.log(minNonNegative([-3,2,5,-9]))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>