j4ub4a
Last Updated: February 25, 2016
·
803
· michd
Mich400x400

Put your opening braces on the same line in JS

It is very common to use the following style for blocks in JavaScript:

// Recommended
if (condition) {
    // ... Some code ...
}

as opposed to:

// Not recommended 
if (condition)
{
    // ... Some code ...
}

While you may think this is generally personal preference, in JavaScript there is a good reason to do it the former way. Thanks to automatic semicolon insertion, the following code would not do what you expect.

function foo() {
    return
    {
        bar: "foobar"
    };
}

Calling foo() will in this case return undefined, because the JavaScript interpreter automatically inserts a semicolon after the return keyword.

You can avoid this behavior by making it your standard practice to open blocks (or object literals) on the same line, like so:

function foo() {
    return {
        bar: "foobar"
    };
}

This will cause foo() to return the expected {bar: "foobar"} object.

As an additional tip, never rely on automatic semicolon insertion. Terminate each and every one of your statements with a semicolon; it will be easier to read your code (less time spent figuring out how the interpreter will shape the behavior), and it is less likely to break in minifiers and/or concatenators.

Say Thanks
Respond

2 Responses
Add your response

3344
D42a7264714dee5006b9c99d2567a320

Good point, I never actually thought that ASI can be a reasoning for same-line braces. Now I have a good reason to make other people put them on the same line! :)

over 1 year ago ·
3346
Mich400x400

@dpashkevich I'd always been used to putting my opening braces on a new line (from in PHP originally), but this argument, which you can easily test, won me over for same-line braces. Saves some LOC too. :-)

over 1 year ago ·