JavaScript formatting: must braces be on the same line as the if/function/etc keyword? [duplicate]
Asked Answered
T

2

5

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 their own lines for readability and so that they can line-up with the closing brace; thus:

if (true)
{
    ...
}

but in JS they should be kept on the same line, in case there are problems with browsers incorrectly interpretting it.

if (true) {
    ...

Is the above italic part a legitimate concern?

PS - I suspect that this question has been asked on here already, but I've not found a question that exactly matches mine. Apologies if it's there and I didn't find it.

Timeout answered 18/10, 2010 at 15:8 Comment(2)
See https://mcmap.net/q/16355/-strangest-language-feature/…Lap
Ugh. Those types of coding standards are stupid.Archives
M
14

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'
    };
}
Mcclelland answered 18/10, 2010 at 15:15 Comment(0)
E
4

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.

Euphemiah answered 18/10, 2010 at 15:10 Comment(1)
I've also heard the feature referred to as automatic semicolon insertion.Meraree

© 2022 - 2024 — McMap. All rights reserved.