0
function every(array, predictate){
    array.forEach(function(x){
    if (!predictate(x))
        {
        return false;
        }
    });
    return true;
}


console.log(every([NaN, NaN, NaN], isNaN));
//true
console.log(every([NaN, NaN, 4], isNaN));
//suppose to return false, but still return true...

The second console.log should return false but it returns true. What did i do wrong?

sdgluck
  • 24,894
  • 8
  • 75
  • 90
Blue Moon
  • 189
  • 1
  • 11

2 Answers2

2

The return false is the return of the anonymous function used in the forEach. So it does not return anything for every. If you want to use forEach and return false, you have to do like this :

function every(array, predictate) {
    var result = true;

    array.forEach(function(x) {
        if (!predictate(x)) {
            result = false;
        }
    });

    return result;
}
Magus
  • 14,796
  • 3
  • 36
  • 51
  • I think i almost get it. Do you think you can clarify it a bit more? "The return false is the return of the anonymous function used in the forEach." You're referring to function(x)? Why it couldn't return false? I'm sorry if i don't make any sense. – Blue Moon Jan 07 '16 at 13:06
  • 1
    Yes i refer to `function(x)`. This function can return false, and that's what you are doing. But `every` will not return false just because the anonymous function return false. – Magus Jan 07 '16 at 13:07
  • Oh I see what you mean... because i'm calling every not the anonymous function that's why i want the every to return false not the anonymous function. I've been going at this for a while. I finally got it. Thanks. – Blue Moon Jan 07 '16 at 13:09
1

Your return false statement is for the forEach callback function, not for the external every.

every will always return true unless you change it to something like:

function every(array, predictate){
    var retValue = true;
    array.forEach(function(x){
    if (!predictate(x))
        {
        retValue = false;
        }
    });
    return retValue;
}
Shomz
  • 37,421
  • 4
  • 57
  • 85