Sugaring the switch()

liorean liorean at gmail.com
Fri Sep 5 21:35:56 PDT 2008


2008/9/6 Michael Haufe <TNO at thenewobjective.com>:
> I didn't see this mentioned yet, so I'd like to propose implementing a
> feature available in VB.NET that I think would be valuable in ES. Some
> sugar for the switch() block:
>
> switch(foo){
>    case 1,2,3:
>        //stuff...
>    break;
>    case a,b,c:
>        //stuff...
>    break;
> }

This is already valid ECMAScript 3. Run the following in any browser and see:

    var
        t=2;
    switch(t){
        case 1,2,3:
            alert('1,2,3');
            break;
        default:
            alert('default');
            break;
    }

As you can see, the "1,2,3" part is treated as an expression list,
that is each expression is executed in order and the result of the
last one is the return value of the whole expression list. In other
words that is equivalent to

    var
        t=2;
    switch(t){
        case 3:
            alert('3');
            break;
        default:
            alert('default');
            break;
    }

> Would be equivalent to:
>
> switch(foo){
>    case 1:
>        //stuff...
>    break;
>    case 2:
>        //stuff...
>    break;
>    case 3:
>        //stuff...
>    break;
>    case a:
>        //stuff...
>    break;
>    case b:
>        //stuff...
>    break;
>    case c:
>        //stuff...
>    break;
> }

This would be a backwards incompatible change, and as such is a
no-fly. I don't think changing semantics for existing established
syntax will be an option. If you want to introduce new semantics, you
need to make them either take place in normal host objects or add
specific new syntactic forms for those semantics.
-- 
David "liorean" Andersson


More information about the Es-discuss mailing list