macsig macsig - 8 months ago 49
Javascript Question

Returning false from an else clause

I have the following code

elements.filter(function(_, e){
terms.forEach(function(term) {
returnValue = true;
if(...) {
} else {
returnValue = false;
return returnValue;

and I'm wondering if there is a cleaner way to
return false
directly from the
clause instead of using a temporary variable since it is kind of annoying to be forced to use


Answer Source

Use array#every - that page has polyfill for elderly browsers

elements.filter(function(_, e) {
    return terms.every(function(term) {
        if (...) {
            return true;
        } else {
            return false;

Note that you return term.every....

Array#every calls the callback until the callback returns false, in which case the value returned by Array#every will be false, if all iterations return true, the value returned by Array#every will be true ... so every return must be true for it to return true, otherwise it returns false and stops iterating