Dangerous implications of Allman style in JavaScri

2019-01-01 11:52发布

问题:

I cannot remember where, but recently I passed a comment where the user told that 1TBS is more preferred than Allman in JavaScript and said Allman has dangerous implications in JavaScript.

Was it a valid statement? If so, why?

回答1:

return cannot have LineTerminator after it so:

return
{


};

is treated as return; (return undefined) instead of return {}; (return an object)

See the rules for Automatic Semicolon Insertion (ASI) for more.



回答2:

It is a valid statement.

Because JavaScript\'s engines have what\'s called ASI (Automatic Semicolon Insertion) which inserts a semicolon if necessary at lines returns. The \"if necessary\" is ambiguous; sometimes it works and sometimes doesn\'t. See the rules.

So, as said in the other answers:

return
{
};

// Is read by the JavaScript engine, after ASI, as:
return; // returns undefined
{ // so this is not even executed
};

So it\'s not recommended for return statements.

However, if your guidelines recommend the Allman style for function declarations, it\'s perfectly fine. I know some that do.



回答3:

I think it depends on the statement. For example a return statement might be broken if opening brace is on new line. More info here.



回答4:

return {
    a: \"A\",
    b: \"B\"
};

// vs.

return // Semicolon automatically inserted here! Uh oh!
{
    a: \"A\",
    b: \"B\"
}