Home > Mobile >  Is it good practice to surround code with braces?
Is it good practice to surround code with braces?

Time:10-25

Is it okay to surround code with braces { } for making code in IDE's compress/collapse?

For example:

{
    function foo(a,b) {
        return a*b b;
    }

    function bar(a,b,c) {
        return a*b c;
    }
}

This would collapse in my IDE to the following:

{ ...
}

Are these extra braces allowed, or would it be syntactically incorrect? (I know it works because the code has run without any errors regarding syntax.)

CodePudding user response:

You've already answered your question:

Are these extra braces allowed, or would it be syntactically incorrect?

with

(I know it works because the code has run without any errors regarding syntax)

It is syntactically permitted, as of ES2015.

But, these sorts of plain blocks have some issues:

  • Function declarations inside them work very strangely (so using them is likely to confuse people in some circumstances)
  • They're quite unusual to see - generally, script-writers do not use them, and do not expect them, so using such a block is likely to confuse some

If you need the ability to "compress" code - to group parts of related code without cluttering up a script - consider using modules instead. For example

// fooAndBar.js
export function foo(a, b) {
  return a*b b;
}
export function bar(a, b, c) {
  return a*b c;
}

Then just import the functions when needed.

It's a lot easier to maintain and debug 8 files that are 50 lines each than it is to do the same for one file that's 400 lines each. If you have to collapse blocks to make something easier to read, it's probably time to refactor to another file.

  • Related