I am trying to create an "every" function for an array. I am aware that it is already built-in, but I just want to enhance my programming skills.
let every = (arr, f) => {
for (let element of arr) {
if (f(element)) {
return true
}
else {
return false
}
}
}
console.log(every([2, 4, 6], n => {n % 2 === 0})) // <-- false
Why is it giving me false. Could someone please spot the error? Thank you!
4
Answers
because you function not return.
try this:
Two mistakes:
Either change the test function to
n => {return n % 2 === 0}
orn => n % 2 === 0
Your for loop should return false immediately if any element fails the test. Then, if nothing fails, you return true after the loop.
The problem is that the
every
function is returningtrue
orfalse
based on the first element of the array that is passed into the function. The function should iterate through each element of the array and returnfalse
if any of the elements do not pass the test defined by the callback functionf
.Here is the corrected
every
function:or
Here’s a revised version of your implementation that fixes two issues:
Fixed by returning false if an entry doesn’t pass the test function, and returning true only after all elements have been evaluated.