JavaScript braces on new line or not?

Tower picture Tower · Jul 10, 2010 · Viewed 30.1k times · Source

At work, we place braces on the next line, but at home, I do the opposite. Which one do you prefer? (K&R vs OTBS)

function something() {
    // ...
}

function something()
{
    // ...
}

A lot of JavaScript libraries seem to use the OTBS (one true brace style). I'd like to follow them for consistence among other JavaScript projects, but doesn't K&R style look more readable?

Note: We know the problem with return and braces in JavaScript, that will always be an exception. However, that is only a single case.

Answer

Daniel Vassallo picture Daniel Vassallo · Jul 10, 2010

Douglas Crockford gives a reason for choosing the K&R style1:

I always use the K&R style, putting the { at the end of a line instead of the front, because it avoids a horrible design blunder in JavaScript's return statement.

The blunder he is referring to is how JavaScript handles the return statement differently in the following two scenarios:

return {
   'status': 'ok'
};

... and:

return 
{
   'status': 'ok'
};

The first one will return an object with a status property, while the latter will return undefined because of semicolon insertion.


1 Douglas Crockford: JavaScript: The Good Parts: Style (page 96) - ISBN: 978-0596517748.