8

I remember there is a convention/recommendation to put opening brace in the same line, because of the way JavaScript adds a semicolon or something.

//OK
function blah(){
};

//Probably not OK
function blah() 
{
};

But I don't find a relevant source to confirm/deny this.

Is this true? Or just a myth?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
  • http://stackoverflow.com/questions/3905238/opening-curly-bracket-brace-position-on-code – miccet Feb 24 '11 at 16:33
  • @miccet I think(heard/believe) in javascript it is not just a matter of style. That's what I'm asking. That question is in general. – OscarRyz Feb 24 '11 at 16:35

6 Answers6

25

The issue you are thinking of is for return statements.

return {
  value: 'test'
}

Works fine, but the following does not:

return
{
  value: 'test'
}

JavaScript adds a semicolon after return turning the above into:

return;
{
  value: 'test'
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
6

This post on Elegant Code gives some explanation of automatic semicolon insertion, but in regard to returning objects, not declaring functions.

David Ruttka
  • 14,269
  • 2
  • 44
  • 39
6

Douglas Crockford gives a reason for choosing the K&R style [1]:

"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 (p. 96)

Óscar López
  • 232,561
  • 37
  • 312
  • 386
5

The JavaScript Garden has a chapter about automatic semicolon insertion. It gives good examples when semicolons are added automatically:

JavaScript is not a semicolon-less language, it in fact needs the semicolons in order to understand the source code. Therefore the JavaScript parser automatically inserts them whenever it encounters a parse error due to a missing semicolon.

In your example JavaScript wouldn't encounter an error due to a missing semicolon though.

Daff
  • 43,734
  • 9
  • 106
  • 120
3

There is no issue with declaring functions, but you can get into trouble when returning objects:

function foo()
{ // this is OK

    return
    { // this is BAD!
        name: "bletch"
    };
    // actually returns undefined!
}

A semi-colon is automatically inserted after the return statement, and that will break your code.

Adam Crossland
  • 14,198
  • 3
  • 44
  • 54
-1

It's a myth. function blah() is always required to be followed by a expression block, so makes no difference which style you use. The first style is simply the most widely used form.

RoToRa
  • 37,635
  • 12
  • 69
  • 105