Search code examples
javascriptbraces

Superfluous curly braces


I have a student who likes to wrap large sections of code in curly braces so he can collapse those sections in the code editor. Initially, I balked at it, but couldn't think of a legitimate reason not to allow him to do it. I'm wondering if this practice will create any problems later on.

Example:

var a = 0;
var b = 1;

{  if (a == b){
      alert("a = b");
   }
   else if (a > b){
      alert("a > b");
   }
   else if (a < b){
      alert("a < b");
   }
}

I know there's a debate about braces around single statements inside an if, that's not what I'm talking about. I'm talking about the "parent" braces, if you will, around the series of if/else if statements.


Solution

  • As deceze indicated in his comment, you are incorrect about the braces limiting the scope of the variables.

    var a = "outside";
    {
        var a = "inside";
        var b = "another inside";
    }
    console.log(a); // prints "inside"
    console.log(b); // prints "another inside"
    

    Having said that, if you need to add in braces to make the code easier to navigate (read: ignore) it's a sign that the function is too long and should be broken apart into well named functions.