Different results when using different ways to traverse an array in JavaScript

1

The purpose of my program is to create two functions, some() and every() , which emulate the functions Array.prototype.some() and Array.prototype.every() , respectively.

My code:

function every(array, callback) {
    array.forEach(function(element) {
        if (!callback(element)) {
            return false;
        }
    });
    return true;
}

function everyB(array, callback) {
    for (var i = 0; i < array.length; i++) {
        if (!callback(array[i])) return false;
    }
    return true;
}

function everyC(array, callback) {
    for (element of array) {
        if (!callback(element)) return false;
    }
    return true;
}

These are the 3 versions I made when checking that after executing:

console.log(every([NaN, NaN, 4], isNaN));

the result is true , while:

console.log(everyB([NaN, NaN, 4], isNaN));

and

console.log(everyC([NaN, NaN, 4], isNaN));

return false , which is correct.

The only thing that varies between these 3 functions are the iteration types used to go through the array, and I can not find the reason why every() does not work as expected.

Documentation:

asked by MigherdCas 21.01.2018 в 18:47
source

1 answer

1

This is simple, the forEach () method has no return value undefined .

The documentation "specifies" this behavior.

  

There is no way to stop or cut a forEach loop other than throwing   an exception. If you need such behavior, the .forEach () method    is the wrong tool

For which you will never make the line return false; , the iteration will not be cut and therefore the return true;

will always be executed     
answered by 21.01.2018 / 18:51
source