Block Lambdas: break and continue

David Herman dherman at mozilla.com
Sat Jan 14 09:12:52 PST 2012


On Jan 13, 2012, at 9:04 PM, Axel Rauschmayer wrote:

> I think it’s a valid concern. The idea is: If I can implement my own loops (the nice-looking paren-free syntax feeds that illusion!) then I also want those loops to have break and continue. You could statically determine what construct, say, a break applies to and either throw a BreakException (if it applies to a lambda) or TCP-break (if it applies to an enclosing non-lambda loop). In the examples below, when I see a continue, I look for the innermost enclosing loop braces and the ones belong to list[i].forEach are definitely candidates.

If I understand your suggestion, you're proposing that non-local break and continue should be exposed as standard exceptions, and then implementors of loop-like abstractions could choose to catch them. E.g. you could implement forEach as:

    Array.prototype.forEach = function(f) {
        for (let i = 0, n = this.length; i < n; i++) {
            try {
                f.call(this, this[i], i);
            } catch (e) {
                if (e instanceof BreakException)
                    break;
                else if (e instanceof ContinueException)
                    continue;
                else
                    throw e;
            }
        }
    };

Whereas a function that does *not* want to expose whether it's using loops would simply do nothing with BreakException and ContinueException, and they would propagate out and you'd get the lexical scoping semantics. Meanwhile, break/continue with an explicit target would never be catch-able.

Did I understand your suggestion correctly?

This *may* not violate TCP (I'm not quite sure), but I'm not enthusiastic about the idea. The semantics is significantly more complicated, and it requires you to understand whether a higher-order function like forEach is catching these exceptions or not. So it becomes an additional part of the API of a function. If someone doesn't document what they do with BreakException and ContinueException, then writing callbacks you won't actually be able to predict what `break` and `continue` will do.

Dave



More information about the es-discuss mailing list