JavaScript braces on new line or not? [closed]
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'sreturn
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.
This is a Holy War to which you will never get a usable answer! Just stick with whatever everyone else in the project is using and don't argue!
For what it's worth, I'm a K&Rite. I find the OTBS puts a lot of visual space between an opening structure and the following statement, when those two lines are often strongly related so would be better presented together, without an intervening almost-blank line. I like to keep my blank lines reserved for separating blocks of related statements.
In a coding style which a lot of whitespace anyway, this may be relatively unimportant. But personally I value terseness, so I can keep more of the program on-screen.
I don't buy that having the open-brace on a different column to the close-brace is an issue. It's still easy to see the block shape just from the indents. Unless you're using hanging indents. Don't do that. But that's another Holy War entirely.
I follow Douglas Crockford's JavaScript coding convention, which was inspired by Sun's Java style guidelines.
Here's a link to it: http://javascript.crockford.com/code.html