I am practicing Javascript on my own and I have a question.
I have made a function called "every" which takes in 2 arguments. First argument is an array, and second argument is a boolean function. what "every" function does is it applies the boolean function to every element in the array, and if every one of them returns true, and "every" function returns true, else false.
for example,
console.log(every([NaN, NaN, NaN], isNaN));
// → true
console.log(every([NaN, NaN, 4], isNaN));
// → false
I came up with a solution and it worked.
function every(array, bool) {
for (var i = 0; i < array.length; i++) {
if (!bool(array[i]))
return false;
}
return true;
}
however, I tried to incorporate forEach into the function and came up with this
function every(array, bool) {
array.forEach(function(element) {
if(!bool(element))
return false;
});
return true;
}
but the second one does not work. and I tracked each executing steps with http://www.pythontutor.com/ and found out "bool(element)" part of the function gives me undefined instead of true or false. so my question is why is it giving me undefined? because bool(element) should be same as isNaN(element) in this case.