Are braces necessary in one-line statements in JavaScript?

No

But they are recommended. If you ever expand the statement you will need them.

This is perfectly valid

if (cond) 
    alert("Condition met!")
else
    alert("Condition not met!")

However it is highly recommended that you always use braces because if you (or someone else) ever expands the statement it will be required.

This same practice follows in all C syntax style languages with bracing. C, C++, Java, even PHP all support one line statement without braces. You have to realize that you are only saving two characters and with some people’s bracing styles you aren’t even saving a line. I prefer a full brace style (like follows) so it tends to be a bit longer. The tradeoff is met very well with the fact you have extremely clear code readability.

if (cond) 
{
    alert("Condition met!")
}
else
{
    alert("Condition not met!")
}

Leave a Comment