Search code examples
javascriptjquerystylingcurly-brackets

Is it true that I should use K&R styling when writing javascript?


I didn't realise it until recently, but I use the Allman style when writing javascript code.

According to http://encosia.com/in-javascript-curly-brace-placement-matters-an-example/ I should be using K&R style. This is because in some situations placement of the curly bracket on the next line can cause problems. The problem for me is that I've grown rather fond of the Allman style and would rather not change.

So, my question(s)

  • Is it true that the allman style can cause errors due to the placement of curly brackets in javascript? How about jquery?

  • Is there any trick that would enable me to use Allman style without problems due to curly brackets?

  • Are there any other problems associated with using these styles?


Solution

  • Is it true that the allman style can cause errors due to the placement of curly brackets in javascript?

    Yes, it is. As your link explains, return statements followed by a newline will confuse the parser as it tries to insert a semicolon. This behavior is not limited to returning object literals, though. The following function:

    function foo()
    {
        return
            "bar";
    }
    

    Will also return undefined.

    How about jquery?

    The situation remains exactly the same whether or not jQuery is included.

    Is there any trick that would enable me to use Allman style without problems due to curly brackets?

    Yes, do not use Allman style with object literals. Consider you want to assign an object literal to a variable. Are you really going to write:

    var foo =
    {
        bar: "quux"
    };
    

    Or will you go for:

    var foo = {
        bar: "quux"
    };
    

    IMHO the second snippet is more readable than the first. You can continue using Allman style with the braces inside for, if, while, function, etc., but make an exception for object literals.

    Are there any other problems associated with using these styles?

    return is quite a special case, because it is valid with or without an argument. When confronted with a lone return statement on one line, the parser cannot tell if it should add a semicolon to make the single-line statement valid, or continue to the next lines and hope for the best.

    For this reason, I think this behavior only becomes a problem with return and maybe throw, not other statements.