What is the equivalent of Python any() and all() functions in JavaScript?

The Python documentation gives you pure-python equivalents for both functions; they are trivial to translate to JavaScript:

function any(iterable) {
    for (var index = 0; index < iterable.length; index++) {
        if (iterable[index]) return true;
    }
    return false;
}

and

function all(iterable) {
    for (var index = 0; index < iterable.length; index++) {
        if (!iterable[index]) return false;
    }
    return true;
}

Recent browser versions (implementing ECMAScript 5.1, Firefox 1.5+, Chrome, Edge 12+ and IE 9) have native support in the form of Array.some and Array.every; these take a callback that determines if something is ‘true’ or not:

some_array.some((elem) => !!elem );
some_array.every((elem) => !!elem );

The Mozilla documentation I linked to has polyfills included to recreate these two methods in other JS implementations.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)