javascriptswitch-statementjslint

Is a reversed switch statement acceptable JavaScript?


JSLint is complaining that (true) is a weird condition. Which is understandable if I wasn't using it on a reversed switch statement. So is JSLint wrong or should I not be using reversed switch statements?

Thanks for any help/enlightenment.

switch (true) {
    case (menuLinksLength < 4):
        numberOfColumns = 1;
        break;
    case (menuLinksLength > 3 && menuLinksLength < 7):
        numberOfColumns = 2;
        break;
    case (menuLinksLength > 6 && menuLinksLength < 10):
        numberOfColumns = 3;
        break;
    case (menuLinksLength > 9):
        numberOfColumns = 4;
        break;
    default:
        numberOfColumns = 0;
}

Solution

  • The third edition of the ECMA-262 standard (supported by Firefox 1.0+, Google Chrome 1.0+, MSIE 5.5+ and others) defines that

    switch (expression) {
        case label1:
            statements1
        .
        .
        .
    }
    

    executes statements1 if (expression) matches label1.

    That means that your switch statement is perfectly fine.

    I tried it out on Firefox, Chrome and IE. None complains...

    Edit:

    Now the guessing part:

    JSLint is a code anaylisis tool. When it sees switch (true), it assumes that you don't know what you're doing. Weird doesn't mean necessarily wrong...