2013-01-07

Brace styles and JavaScript

In languages whose syntax is derived from C (e.g.: C ← C++ ← Java ← JavaScript), two brace styles are most common: Allman style and 1TBS.

Allman style

If a statement [1] contains a block, that block is considered as somewhat separate from the header of the statement: its opening brace is in a line of its own, at the same indentation level as the head. For example:
    function foo(x, y, z)
    {
        if (x)
        {
            a();
        } else {
            b();
            c();
        }
    }

1TBS (One True Brace Style)

Here, a block is more closely associated with the header of its statement, it starts after it, in the same line. For example:
    function foo(x, y, z) {
        if (x) {
            a();
        } else {
            b();
            c();
        }
    }
1TBS is a variant of the (older) K&R (Kernighan and Ritchie) style. In K&R style, functions are written in Allman style and braces are omitted where they are not necessary, e.g. around single-statement then-cases.
    function foo(x, y, z)
    {
        if (x)
            a();
        else {
            b();
            c();
        }
    }

JavaScript

The de-facto standard in the JavaScript world is 1TBS, most style guides recommend it. One reason goes beyond taste and fitting in: If you return an object literal, you can’t put the opening brace in a separate line. An object literal is not a code block, but things look more consistent and you are less likely to make mistakes if both are formatted the same way. For example:
    return {
        name: 'Jane'
    };
If you formatted that in Allman style, you’d have:
    // Don’t do this
    return
    {
        name: 'Jane'
    };
However, JavaScript’s automatic semicolon insertion [2] adds a semicolon after return, if it is followed by a newline. The above code is thus equivalent to
    return;
    {
        name: 'Jane'
    };
That’s an empty return statement, followed by a code block (not by an object literal!) whose insides consist of the label name and the expression statement [1] 'Jane'. At the end, there is the empty statement, a semicolon (;) on its own.

The return statement is one of the few cases where newline is significant in JavaScript: it works as a terminator for statements. In the future, newlines might become more significant in JavaScript [3].

My preferences

My personal style is:
  • 1TBS
  • I omit braces in an if-statement if there is no else-case and the then-case has only one or two tokens. I write such if-statements in single lines. For example:
        if (x) return x;
    
  • I indent 4 spaces. I never use tabs for indentation, as they are displayed too differently on various systems.
Obviously, whenever I contribute to an existing project, I stick to the coding style of that project.

References

  1. Expressions versus statements in JavaScript
  2. Automatic semicolon insertion in JavaScript
  3. What JavaScript would be like with significant newlines

16 comments:

Sean McMillan said...

What you have labelled K&R is really the Allman style (AKA ANSI Style.) K&R proper cuddles the braces of control structures, but not functions. 1TBS is considered a variant of K&R that cuddles the functions braces too.

(In fact, I personally thought that K&R == 1TBS, and only in saying "wait a minute..." when rerading this article and looking it up did I find out what the difference was.)

Axel Rauschmayer said...

True. Fixed it. Wikipedia has it partially wrong.

Erick Mendoza said...

4 spaces vs. tab: the controversy continues

Axel Rauschmayer said...

2 spaces versus 4 spaces might be an even bigger controversy. ;-)

Júlio Batista said...

Using the Allman style, in my opinion the braces after the return statement should be in the same line as the statement because it isn't opening a block, it's only defining an object (value).

asperto said...

Thanks. I learned something. (Auto semicolon)

Anonymous said...

Allman is more professional and ensures parity with other languages. Circumventing the 'return' problem using this style is easy:


var resultObj = { ... };
return resultObj;

rtpHarry said...

I always use the braces around the if statement - no point in being "clever" just to trip yourself or a fellow developer up further down the line when an extra statement is added.

rtpHarry said...

Interesting idea although I think I will still use the 1TBS style when writing JavaScript. Its geeky but I like the feel of being able to switch between the styles in the different languages. Yeah thats geek excitement! :P



Also, I'm not an expert in this but I think that a certain set of people get upset if you make var's down at the bottom instead of all at the top?

Florin Jurcovici said...

If you use Allman there's no risk in doing that - the missing opening brace sticks out like a sore thumb. It's only K&R or 1TBS which leads you to assume there's already an opening brace after an if() statement when there isn't one. Which is why I prefer Allman.

Also, K&R didn't actually originate with Kernighan and Ritchie. The publishers publishing the initial C book thought it's a waste of paper to use braces the way the users used them in code samples (supposedly Allman-style), and thus moved the opening brace at the end of the previous line. A lot of people sheepishly copied what they saw in the book, and this is how the K&R style was born.

Also, if you consistently use tabs for indentation only, and spaces for alignment, your code will look good in every editor, regardless of tab size (unless you're doing ASCII art, where the contents of one line have to vertically align with the previous/next line, which is stupid in itself - a simple rename might break your formatting). By using spaces, you just force your indent preferences on everybody else working on that code.

Skizz said...

Style is irrelevant and a distraction - readability and understandability is far more important! It's no good having your braces in the places you like the most when all your variables are named temp1, temp2, temp3, etc... and none of your code is documented!

rtpHarry said...

Yeah I agree, Allman is the best style for readability and maintenance. Not sure if I made it clear, I was referring to the practice of omitting braces from if statements with a single statement in them.

When I first started coding I thought it was clever to take advantage of it but then I realised it would only lead to hard to spot errors. After spending any amount of time searching for these I think we all gain an appreciation that doing anything to prevent them makes sense.

Alberto Arena said...

Thanks, this was really useful, especially for automatic semicolon insertion when returning object literals.

Axel Rauschmayer said...

Opinions on how to best use `var` differ widely. I’ve written down my opinions here:
http://www.2ality.com/2012/11/var-statement-rules.html

K said...

Allman is for sissies.

Axel Rauschmayer said...

Not if you want parity with Java where 1TBS dominates (as it does for JavaScript at the moment).

Web Analytics