let/const in switch cases

Luke Hoban lukeh at microsoft.com
Thu Aug 9 18:38:56 PDT 2012

According to the current draft spec text 'let'/'const' are allowed in the statement list of a switch case, but contribute to the block scope of the outer block.  This can lead to some confusing situations:

function(x) {
   do {
        switch(x) {
            case 0:
                return x;
            case 1:
                let x = 'let';
    } while (foo());

The 'x' in 'case 0' here will bind to the later 'let x', but depending on which case executes first, this may or may not trigger an error on accessing x before it is defined.  This is the only place in the language where a reference to a let binding declared in the same block scope as the reference cannot be statically understood to be a valid vs. invalid read.  This is both likely to cause confusion for developers, and adds implementation complexity.  

There's an argument to be made that switch case StatementLists should not be allowed to include Declarations.  This would make the code above a syntax error, and require putting {} around the case if 'let'/'const' were needed.  This also aligns with all other occurrences of nested statements that are not surrounded by {} in the grammar, for example, 'if(true) let x = 3'.  Current Chrome builds appear to follow this approach, reporting that the 'let' in the initial code sample above appears in an 'unprotected statement context'.  


More information about the es-discuss mailing list