I remember there is a convention/recommendation to put opening brace in the same line, because the way Javascript add 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?
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.The JavaScript Garden has a chapter about automatic semicolon insertion. It gives good examples when semicolons are added automatically:
In your example JavaScript wouldn't encounter an error due to a missing semicolon though.
This post on Elegant Code gives some explanation of automatic semicolon insertion, but in regard to returning objects, not declaring functions.
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:
... and:
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)
The issue you are thinking of is for
return
statements.Works fine, but the following does not:
JavaScript adds a semicolon after
return
turning the above into:There is no issue with declaring functions, but you can get into trouble when returning objects:
A semi-colon is automatically inserted after the return statement, and that will break your code.