Curly Braces Not Required

In the Javascript 1 course Mosh removes all the curly braces from the If…Else saying they made the code cluttered. I thought curly braces to separate code blocks are required to avoid runtime errors. I also thought it was part of good coding etiquette. Can someone tell me how the code can run without the braces?

I think you should add curly braces if there are more than one statement. If you only have one statement then its not necessary to add curly braces.

1 Like

It is actually stronger than that:

If you want to use more than one statement after an if or else statement, you must enclose the statements in curly braces, {}.

Source: Oracle’s documentation

So the braces are optional if there is exactly one statement, otherwise they are required.

Some style guides require always using them. For example, Google’s JavaScript style guide:

Braces are required for all control structures (i.e. if , else , for , do , while , as well as any others), even if the body contains only a single statement.

With a mild exception for improved readability:

A simple if statement that can fit entirely on a single line with no wrapping (and that doesn’t have an else) may be kept on a single line with no braces when it improves readability.

Thanks for the explanation. I’m very new to JS so I’ll just use brackets.

1 Like