javascriptloopsforeachbreakcontinue

How can I emulate a 'break' or even a 'continue' inside a 'forEach' loop?


Here is what I would like to do. However there's no "continue" inside a forEach.

    var que = null
    self.qs.forEach((q) => {
        if (q.synchronized == false) {
            que = q;
            break; // I would like to do this
        }
    });
    //  Now que would be set to the first not synchronized

Can anyone tell me how I can do this. Note that I am using the latest browsers. Please note I am only looking for one object in the array where synchronized == true. Sorry I used "continue" in my question earlier. The functionality I am looking for is "break".


Solution

  • you can use Array.prototype.some:

    short form:

    self.qs.some((q) => {
       return (q.synchronized == false) && (que = q, true);
    });
    

    or:

    self.qs.some((q) => {
       if (q.synchronized == false)
       {
          que = q;
          return true;
       }
    });
    

    or:

    self.qs.some(q => (q.synchronized == false) && (que = q, true));
    

    Array.prototype.some returns on the first result that returns true.

    Array.prototype.every returns on the first result that returns false.

    They are basically tests for:

    You can abuse this for something you want here :-)

    The 3rd example is a bit of JS-fu but generates a nice oneliner ^_^

    full code:

    var que;
    self.qs.some((q) => {
       if (q.synchronized == false)
       {
          que = q;
          return true;
       }
    });
    if (que) {
       // handle que here
    }
    

    Unoptimized dirty hack:

    You could also use reduce for this:

    var que = self.qs.reduce((result, q) => {
        if (que != null) return result;
        return (q.synchronized == false) ? q : result;
    }, null);
    // js-fu version
    var que = self.qs.reduce((result,q) => que || (q.synchronized == false ? q : que),null);
    

    Very unoptimized, but it saves you defining a var... It has no early out though.