Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript switch statement - default first OK?

This is very similar to default as first option in switch statement? , but regarding JS rather than PHP.

I have a helper function that wraps various calling styles for another function. The wrapped function requires at least one, and can accept up to 4 parameters. What I am doing is fairly well described by this minimum code example, which works fine in my versions of Chrome and FF.

function testSwitch(definition) {
    var term, minLength, boundaryStart, boundaryEnd;
    switch (definition.length) {
        default:
    case 4:
        boundaryEnd = definition[3];
    case 3:
        boundaryStart = definition[2];
    case 2:
        minLength = definition[1];
    case 1:
        term = definition[0];
        break;
    case 0:
        console.log('fail')
        return;
    }
    console.log(term, minLength, boundaryStart, boundaryEnd);
}

(In the real use case they are passed to the actual function rather than console.log). So the idea is to fall through the cases, allowing too many parameters to be provided (but ignoring the extra ones), but failing if the definition provided is empty.

So I know from my testing that this appears to work in some browsers at least, can I rely on this working across reasonably recent browsers (eg iOS/Android devices, IE8+, Edge etc)? I know that excluding the break statement is well-defined behavior and used fairly broadly, but am not so sure about having the default case first and empty (eg. if some browsers JS engines would optimize out the empty default case then this doesn't work for me, as it would not work when called with an array of size 5, for example).

like image 411
Chris O'Kelly Avatar asked Aug 03 '16 00:08

Chris O'Kelly


1 Answers

I've never seen someone use this approach before. It's clever. As a side note, clever is a two-edged blade; if this is code that anyone other than you will be touching, I strongly suggest a comment there to make it clear you did that on purpose or someone is going to alter it (because it 'looks wrong') and break it without realizing the intent.

The documentation indicates that default is not required to be the last clause.

If you find a browser were it does NOT work, you could modify it slightly thus and avoid the default:

function testSwitch(definition) {
    var term, minLength, boundaryStart, boundaryEnd;
    switch (definition.length > 4 ? 5 : definition.length) {
    case 5:
    case 4:
        boundaryEnd = definition[3];
    case 3:
        boundaryStart = definition[2];
    case 2:
        minLength = definition[1];
    case 1:
        term = definition[0];
        break;
    case 0:
        console.log('fail')
        return;
    }
    console.log(term, minLength, boundaryStart, boundaryEnd);
} 
like image 50
S McCrohan Avatar answered Nov 15 '22 09:11

S McCrohan