Skip to content Skip to sidebar Skip to footer

Javascript Formatting: Must Braces Be On The Same Line As The If/function/etc Keyword?

Possible Duplicate: why results varies upon placement of curly braces in javascript code We have company policies that dictate that in PHP opening curly braces should be on the

Solution 1:

Yes, it matters in certain corner cases.

And the problem isn't with "browsers incorrectly interpreting it". The dodgy behaviour is correct according to the ECMAScript specifications. A JavaScript implementation that didn't exhibit this behaviour would not be spec-compliant.

An example. This function is broken:

function returnAnObject {
    return
    {
        foo: 'test'
    };
}

It's supposed to return an object, but actually returns nothing. JavaScript interprets it like so:

function returnAnObject {
    return;
    {
        foo: 'test'
    };
}

Solution 2:

The interpretation in JS, is usually when you have line without semi-colon, it is by default added at the end of line. To avoid such things and to increase readability, the braces are usually added on same line as IF, WHILE, Function etc.

This feature in JS is referred to as implicit semicolon insertion as far as I know.

Post a Comment for "Javascript Formatting: Must Braces Be On The Same Line As The If/function/etc Keyword?"