Alex Rivera | Logout

PHP vs. JavaScript switch indentation

Asked 2011-01-21T16:36:50.077
11

While I realize that each language has its own convention for indentation, I can't help but be annoyed with something I've recently discovered. Consider this code from the PHP manual:

switch ($i) {
    case "apple":
        echo "i is apple";
        break;
    case "bar":
        echo "i is bar";
        break;
    case "cake":
        echo "i is cake";
        break;
}

Notice that each case is indented from the switch statement. This makes sense, as the code is easier to read and the body of the block is contained one level inside of it.

However, when I test the equivalent JavaScript switch statement in JSLint:

switch (i) {
    case "apple":
        alert("i is apple");
        break;
    case "bar":
        alert("i is bar");
        break;
    case "cake":
        alert("i is cake");
        break;
}

...it displays an error telling me that it should appear like this instead:

switch (i) {
case "apple":
    alert("i is apple");
    break;
case "bar":
    alert("i is bar");
    break;
case "cake":
    alert("i is cake");
    break;
}

It seems counterintuitive, as each case is now inline with the switch block itself. I can't imagine any reason why this would be considered better, much less trigger an error.

Is JSLint in err, or is it just following convention? If the latter is true, why wouldn't the convention be to indent for clarity?

Edit
Report

1 Answer

1

While formatting is important, in the end it's your formatting. Do it how you like. The particular style you choose is a personal choice and many styles can be "good". However, any "good" formatting style must be consistent - pick the rules you like and stick to them.

It's kind of funny to me how debates rage over things like placing { on the same line as the preceeding code or not, or "cuddling curly braces" around an else. I think only communists place a { on the same line as their if statement. :)

answered 2011-01-21T16:48:15.193

Your Answer