53

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.

Gert Grenander
  • 16,088
  • 6
  • 37
  • 43
Tower
  • 87,855
  • 117
  • 329
  • 496
  • 9
    @Deleters: Before casting your delete vote, please note that the mix of answers objectively exhaust the advantages and disadvantages of either style in the JavaScript context, without being argumentative... Some answers give a tangible reason for using the K&R style (due to the semicolon insertion issue), and cite a very authoritative source (Crockford). – Daniel Vassallo Jul 12 '10 at 03:44
  • 4
    Indeed, I think this question has technical reasons (see @Daniel's answer) for not being subjective and rather being extremely constructive. – Kirk Woll Jun 24 '11 at 01:51
  • 4
    While we fight this endless battle, python programmers are laughing their assses off :D – Tadej Magajna Nov 27 '11 at 00:41
  • 2
    And no, K&R is not more readable to some people. Like me. Particularly when there's code in there, not just a // ... – Almo Jul 11 '12 at 19:20
  • I'm really surprised there hasn't been any research into loss of productivity when almost half the displayed lines on the screen are a single `{`. Think of `} else {` for example, is 3 lines instead of 1 using that style. – NoBugs Jan 29 '15 at 11:48
  • If you prefer to use OTBS, then be aware of automatic semicolon insertion (ASI) rules. – yusuf tezel Jan 11 '17 at 09:38

9 Answers9

157

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.

Daniel Vassallo
  • 312,534
  • 70
  • 486
  • 432
  • 11
    This is just a single case, where you can make an exception if you are using braces on new line. – Tower Jul 10 '10 at 10:57
  • 25
    @rFactor: Yes, it is just a case and you could make an exception for this case... But I see the point in remaining consistent, and not making exceptions for the return statement. On the other hand, I like the K&R style, so it's all good for me :) – Daniel Vassallo Jul 10 '10 at 11:04
  • 7
    You do not need to make exceptions to coding conventions. Just set the object to a temporary variable and let it return the temporary variable. – Tower Jul 10 '10 at 14:34
  • 12
    Wow - I disagree with Crockford, and anyone else really, on picking a coding convention based on a single, rarely-seen, kludge-driven behavior. I lost a little respect for the guy because of this. – Jeff Meatball Yang Jul 11 '10 at 05:26
  • 26
    @Jeff, why is returning an object created on-the-fly from a function an example of "kludge-driven behavior"? Having a style that does not require exceptions to it is certainly an entirely reasonable point of view. – Kirk Woll Jun 24 '11 at 01:49
  • 5
    @Kirk, I think you misunderstand me. The kludge-driven behavior to which I referred was the insertion of an EOL semi-colon. Why would Crockford cite such a menial and kludgy behavior as his pivotal motivation for choosing a coding style? – Jeff Meatball Yang Jun 27 '11 at 02:42
  • I think the OP was referring for curly braces after "function", "for", "while", "switch" statemens. "return" is a different case... I personally put curly braces in single lines, I find the code more readable. – Paolo Feb 20 '14 at 11:27
  • 1
    here's the video: http://youtu.be/hQVTIJBZook?t=30m37s – Michał Šrajer May 19 '14 at 16:04
  • 1
    I think remaining constant is import, but validating the K&R brace style just because of object literal declarations still doesn't mean the code is more readable. The Allman style is the easiest to read, and readability should be valued more by JavaScript programmers. – Chunky Chunk Jun 24 '16 at 15:14
  • I've just encountered the exact same problem as you're describing, but with the "throw" keyword. Very useful information to know. – Wibbler Jun 04 '18 at 22:45
  • Related: [What are the rules for JavaScript's automatic semicolon insertion (ASI)?](https://stackoverflow.com/q/2846283/3258851) – Marc.2377 Mar 11 '19 at 14:18
35

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.

bobince
  • 498,320
  • 101
  • 621
  • 807
  • 1
    Do you use this convention for other languages, too? Like PHP? – Tower Jul 10 '10 at 10:56
  • 6
    Personally, when I'm the one that decides, yes. If I'm not, because I'm part of a wider project, I'm not going to force what is a largely-unimportant preference on everyone else. – bobince Jul 10 '10 at 11:03
  • 8
    For most languages I agree that this is a pointless holy war and that consistency should be the deciding factor, but I think for Javascript the automatic insertion of semicolons provides a real technical argument for inlined opening braces. Not sure I entirely agree with it, but it _is_ a technical, rather than religious, argument. – Keith Jun 03 '13 at 14:48
  • I completely agree with @Keith here. – Bart Hofland Aug 07 '19 at 06:34
19

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

Daniel Vassallo
  • 312,534
  • 70
  • 486
  • 432
dalton
  • 3,556
  • 1
  • 22
  • 25
  • I wanted to add the same link. So +1 for you: you are more quickly! Moreover I recommend always verify your javascript code with JSLint (see http://www.jslint.com/). By the way, one can verify that both styles of placing of braces are correct. – Oleg Jul 10 '10 at 10:46
  • 2
    great point, cause brace placement really matters – Konstantin Chernov Dec 08 '14 at 13:55
14

In my opinion, it depends on who else will be working with your code. If you work on a C# team and share a lot of responsibilities, put it on a new line and avoid the inevitable bickering that would otherwise follow. If you work with a lot of PHP (or older JS programmers), put it on the first line for the exact same reason.

But if you're looking for something more authoritative, Douglas Crockford says that the opening brace should always be on the top line. His reasoning, if I remember correctly, is that it makes it consistent with the rest of the language. Basically, because this is valid but (probably) incorrect code:

function myFunc() 
{
    return 
    {
      ok: true
    };
} 

...you should universally avoid putting open-braces on a new line. Why? Because programming style should not lead to syntactic ambiguity.

The sample code above is valid because it is completely syntactically correct and no exceptions will be raised if you write this. However, instead of returning an object literal, {ok:true}, it will return undefined and the code below it will not be reached. Put the opening braces up one line and it will return the object literal you were, perhaps, expecting.

The question is, do you find that argument compelling enough?

Andrew
  • 12,936
  • 13
  • 52
  • 102
  • 9
    Not compelling at all. My coding convention: A. Use whatever brace style you want. B. Any construct that is DEPENDENT ON BRACE STYLE is FUBAR, and should be avoided, as convention. – Jeff Meatball Yang Jul 11 '10 at 05:30
  • I don't have a clue about JS but it seems to me that this behavior becomes less illogical when you visualize that you are doing the following things: 1) you return no value 2) you create an anonymous dictionary with the content "ok = true". So it's not an argument against the OTBS because trying to separate the return statement from its argument is just bad coding style - indifferent what brace style you use. –  Dec 17 '10 at 12:20
5

Neither one is better than the other. Just choose one and use it consistently.

βξhrαng
  • 41,698
  • 21
  • 103
  • 145
  • 1
    I agree that consistency is the most important factor, but the first one saves some horizontal space and thats why I now prefer it. – grm Jul 10 '10 at 11:40
  • @grm: I also prefer the first style, because it is more like Java's naming conventions that I am used to. But one can argue that the second style results in more readable code. However in the end, IMHO, compared to more important factors related to writing correct and maintainable JavaScript code, and also by considering the fact that most IDEs can format the code in either way in one click (IntelliJ IDEA and WebStorm can do this), this issue loses its importance. – βξhrαng Jul 10 '10 at 17:09
4

All subjective. Some are slightly better but the difference is negligible. The most important thing to do is stay consistent across all your code.

Personally, I prefer the tucked in style, with 4 space 'real' tabs.

function a() {
    if (b) {
        do;
    } else {
        do2;
    }
}
Delan Azabani
  • 73,106
  • 23
  • 158
  • 198
  • Not everyone likes spaces, I use tabs. I wouldn't go through all my code converting tabs to spaces (even with the replace function). The code you write is code you should submit here. Give or take.. – Barrie Reader May 04 '14 at 09:27
3

I prefer them on the same line, but mostly because I pass anonymous functions as arguments a lot...it saves some space and makes the function definition look less jarring. Of course, this is just an opinion, and I agree with Bytecode Ninja that consistency is the most important thing.

Faisal
  • 4,425
  • 1
  • 16
  • 13
0

As stated in many answers, its mostly important that you find a style that you (and/or your team mates, if applicable) stick to. Personally I prefer same line as I've found that putting curly braces on the new line can lead to lots of near blank lines if you're working with closures and nested functions, which makes code less readable for me (although, probably not for most people...)

Jake
  • 1,018
  • 6
  • 10
0

I prefer the K&R method for the same reasons listed above. It looks more compact, and the two relevant lines are grouped together.

computersaurus
  • 175
  • 1
  • 1
  • 11