Search code examples
javascriptsyntaxif-statementtry-catchcurly-braces

Can curlies be omitted for try and/or catch blocks, as for if and else ones?


if (foo) {
  bar;
}

can be shortened to

if(foo) bar;

since it's only one statement in the block.

I'm wondering if the same applies to try/catch... I don't like extra cruft in my code.


Solution

  • According to ECMAScript 5, a block is required, which means you need the curly braces.

    https://es5.github.io/#x12.14

    TryStatement :

    try Block Catch

    try Block Finally

    try Block Catch Finally

    Catch :

    catch ( Identifier ) Block

    Finally :

    finally Block

    https://es5.github.io/#x12.1

    Block :

    { StatementList opt }

    StatementList :

    Statement

    StatementList Statement