In a JavaScript ‘switch’ block, JSLint expects every ‘case’ statement to be broken with a ‘default’ keyword.

So, the following code sample will fail:

var x = 0;
switch(x){
    case 1:
        x++;
        //where's the 'break;'?
        //so, 'fall through'
    case 2:
        x--;
        break;
    default:
        break;
}

In this sample, after evaluating ‘true’ for ‘case 1′ and executing the adjacent code, the interpreter will ‘fallthrough‘ to the next clause and test that. In the above code the next clause will evaluate false, so there is not a problem.

Many consider this an advantageous language feature. Consider the scenario where you want to execute the same code under two different circumstances (i.e. implement an ‘or’ equivalent). For example:

var x = 0;
switch(x){
    case 1: //fallthrough
    case 2:
        x--;
        break;
    default:
        break;
}

Douglas Crockford, however considers this to be a little too tricky. In his book ‘JavaScript: the good parts’, he mentions this:

I want to avoid idioms that look like mistakes.

I never allow switch cases to fall through to the next case. I once found a bug in my code caused by an unintended fall though…

He goes on to explain that language features that are sometimes useful, but occasionally dangerous are probably best avoided as it can be difficult for a developer/reviewer/maintainer to differentiate its use from a bug.

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

, ,
Trackback

3 comments untill now

  1. [...] [...]

  2. I have never said that it is not useful. I said that it is error-prone and unnecessary. By avoiding unnecessary features, the errors are avoided as well. That is a good trade-off. Programming is all about making good trade-offs.

  3. @Douglas Crockford: I never intended to imply that you said it wasn’t useful. I happen to be in agreement with your sentiment on this. I have removed the offending paragraph.

Add your comment now