0

I'm working through Eloquent Javascript and there's an exercise to make an every function, which takes an array and a function and returns true or false depending on what all the items in the array return after going through the function.

I'm confused because when I do console.log() within the function, I get the boolean twice...but when I do console.log(every(arr, func)), I get undefined.

var every = function(arr, req){
    arr.map(function(item){
        return req(item);
    }).reduce(
        function(total, num){

            // this returns: true
            //               true
            console.log(total && num);

            return total && num;
    });


}

// This returns undefined
console.log(every([NaN, NaN, NaN], isNaN));

So why do I get true twice inside my function, and why do I get undefined?

I'm using node as a console.

2
  • 4
    you never returned anything from every, so console.log(every(...)) will always be undefined. Commented Sep 18, 2015 at 21:26
  • The missing return aside, you really should just use arr.every(req), and if you go for reduce nonetheless you should always pass an initial accumulator value to cover empty arrays. Commented Sep 19, 2015 at 14:38

1 Answer 1

2

You need to add a return statement to your outermost function, like this:

var every = function(arr, req){
    return arr.map(function(item){
        return req(item);
    }).reduce(
        function(total, num){ 
            return total && num;
    });
}

// This returns true
console.log(every([NaN, NaN, NaN], isNaN));

EDIT: Fixed return value, thanks @Kevin B

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

1 Comment

@KevinB absolutely, my bad.

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.