Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript open brace in the same line

Tags:

javascript

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?

like image 331
OscarRyz Avatar asked Feb 24 '11 16:02

OscarRyz


3 Answers

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'
}
like image 177
Rocket Hazmat Avatar answered Nov 07 '22 13:11

Rocket Hazmat


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

like image 30
David Ruttka Avatar answered Nov 07 '22 15:11

David Ruttka


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)

like image 20
Óscar López Avatar answered Nov 07 '22 15:11

Óscar López