1

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.

1 Answer 1

1

The return statement in the .forEach() version returns from the .forEach() callback, not from your enclosing function.

Your application is not really a good use case for .forEach(). You don't really want to execute the function for each element in the array: you only want to process the array up to the first false element. The Array prototype already has a .every(), so you could use that, but then the whole point of your function would be in question :)

Sign up to request clarification or add additional context in comments.

2 Comments

what would I have to do if I wanted the second version to work?
@user3248608 well, you could have the callback function set a flag in the closure, but there's not much of a point to do it - you really want a simple for loop in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.