Are braces necessary in one-line statements in JavaScript?

I once heard that leaving the curly braces in one-line statements could be harmful in JavaScript. I don't remember the reasoning anymore and a Google search did not help much.

Is there anything that makes it a good idea to surround all statements within curly braces in JavaScript?

I am asking, because everyone seems to do so.

Answers:

Answer

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!")
}
Answer

There's a readability aspect - in that when you have compound statements it can get very confusing. Indenting helps but doesn't mean anything to the compiler/interpreter.

var a;
var b;
var c;

//Indenting is clear
if (a===true)
  alert(a); //Only on IF
alert(b); //Always

//Indenting is bad
if (a===true)
  alert(a); //Only on IF
  alert(b); //Always but expected?

//Nested indenting is clear
if (a===true)
  if (b===true)
    alert(a); //Only on if-if
alert (b); //Always

//Nested indenting is misleading
if (a===true)
  if (b===true)
    alert(a); //Only on if-if
  alert (b); //Always but expected as part of first if?

//Compound line is misleading
//b will always alert, but suggests it's part of if
if (a===true) alert(a);alert(b); 
else alert(c); //Error, else isn't attached

And then there's an extensibility aspect:

//Problematic
if (a===true)
  alert(a);
  alert(b); //We're assuming this will happen with the if but it'll happen always
else       //This else is not connected to an if anymore - error
  alert(c);

//Obvious
if (a===true) {
  alert(a); //on if
  alert(b); //on if
} else {
  alert(c); //on !if
} 

The thinking goes that if you always have the brackets then you know to insert other statements inside that block.

Answer

The question asks about statements on one line. Yet, the many examples provided show reasons not to leave out braces based on multiple line statements. It is completely safe to not use brackets on one line, if that is the coding style you prefer.

For example, the question asks if this is ok:

 if (condition) statement;

It does not ask if this is ok:

 if (condition)
   statement;

I think leaving brackets out is preferable because it makes the code more readable with less superfluous syntax.

My coding style is to never use brackets unless the code is a block. And to never use multiple statements on a single line (separated by semicolons). I find this easy to read and clear and never have scoping issues on 'if' statements. As a result, using brackets on a single if condition statement would require 3 lines. Like this:

 if (condition) {
   statement;
 }

Using a one line if statement is preferable because it uses less vertical space and the code is more compact.

I wouldn’t force others to use this method, but it works for me and I could not disagree more with the examples provided on how leaving out brackets leads to coding/scoping errors.

Answer

Technically no but otherwise absolutely Yes!!!

Forget about "It's personal preference","the code will run just fine","it has been working fine for me","it's more readable" yada yada BS. This could easily lead to very serious problems if you make a mistake and believe me it is very easy to make a mistake when you are coding(Don't belive?, check out the famous Apple go to fail bug).

Argument: "It's personal preference"

No it is not. Unless you are a one man team leaving on mars, no. Most of the time there will be other people reading/modifying your code. In any serious coding team this will be the recommended way, so it is not a 'personal preference'.

Argument: "the code will run just fine"

So does the spaghetti code! Does it mean it's ok to create it?

Argument: "it has been working fine for me"

In my career I have seen so many bugs created because of this problem. You probably don't remember how many times you commented out 'DoSomething()' and baffled by why 'SomethingElse()' is called:

if (condition) 
    DoSomething();
SomethingElse();

Or added 'SomethingMore' and didn't notice it won't be called(even though the indentation implies otherwise):

if (condition)
  DoSomething();
  SomethingMore();

Here is a real life example I had. Someone wanted to turn of all the logging so they run find&replace "console.log" => //"console.log":

if (condition) 
   console.log("something");
SomethingElse();

See the problem?

Even if you think, "these are so trivial, I would never do that"; remember that there will always be a team member with inferior programming skills than you(hopefully you are not the worst in the team!)

Argument: "it's more readable"

If I've learned anything about programming, it is that the simple things become very complex very quickly. It is very common that this:

if (condition) 
    DoSomething();

turns into the following after it has been tested with different browsers/environments/use cases or new features are added:

if (a != null)
   if (condition) 
      DoSomething();
   else
      DoSomethingElse(); 
      DoSomethingMore();
else 
    if (b == null)
         alert("error b");
    else 
         alert("error a");

And compare it with this:

 if (a != null) {
    if (condition) { 
       DoSomething();
    }
    else {
       DoSomethingElse();
       DoSomethingMore();
    }
 } else if (b == null) {
    alert("error b");
 } else {
    alert("error a");
 }

PS: Bonus points go to who noticed the bug in the example above.

Answer

There is no maintainability problem!

The problem with all of you is that you Put semicolons everywhere. You don't need curly braces for multiple statements. If you want to add a statement, just use commas.

if (a > 1)
 alert("foo"),
 alert("bar"),
 alert("lorem"),
 alert("ipsum");
else
 alert("blah");

This is valid code that will run like you expect!

Answer

In addition to the reason mentioned by @Josh K (which also applies to Java, C etc.), one special problem in JavaScript is automatic semicolon insertion. From the Wikipedia example:

return
a + b;

// Returns undefined. Treated as:
//   return;
//   a + b;

So, this may also yield unexpected results, if used like this:

if (x)
   return
   a + b;

It's not really much better to write

if (x) {
   return
   a + b;
}

but maybe here the error is a little bit easier to detect (?)

Answer

There is no programming reason to use the curly braces on one line statements.

This only comes down to coders preferences and readability.

Your code won't break because of it.

Answer

It's a matter of style, but curly braces are good for preventing possible dangling else's.

Answer

Here is why it's recommended

Let's say I write

if(someVal)
    alert("True");

Then the next developer comes and says "Oh, I need to do something else", so they write

if(someVal)
    alert("True");
    alert("AlsoTrue");

Now as you can see "AlsoTrue" will always be true, because the first developer didn't use braces.

Answer

I'm currently working on a minifier. Even now I check it on two huge scripts. Experimentally I found out: You may remove the curly braces behind for,if,else,while,function* if the curly braces don't include ';','return','for','if','else','while','do','function'. Irrespective line breaks.

function a(b){if(c){d}else{e}} //ok  
function a(b){if(c)d;else e}   //ok

Of course you need to replace the closing brace with a semicolon if it's not followed by on other closing brace.

A function must not end in a comma.

var a,b=function()c;  //ok *but not in Chrome
var b=function()c,a;  //error  

Tested on Chrome and FF.

Answer

There are many problems in javascript. Take a look at JavaScript architect Douglas Crockford talking about it The if statement seems to be fine but the return statement may introduce a problem.

return
{
    ok:false;
}
//silent error (return undefined)

return{
    ok:true;
}
//works well in javascript
Answer

I found this answer searching about a similar experience so I decided to answer it with my experience.

Bracketless statements do work in most browsers, however, I tested that bracketless methods in fact do not work in some browser.

As of February 26th 2018, this statement works in Pale Moon, but not Google Chrome.

function foo()
   return bar;
Answer

Not responding the question directly, but below is a short syntax about if condition on one line

Ex:

var i=true;
if(i){
  dosomething();
}

Can be written like this:

var i=true;
i && dosomething();
Answer

There are lots of good answers, so I won’t repeat, except as to say my “rule” when braces can be omitted: on conditions that ‘return’ or ‘throw’ (eg.) as their only statement. In this case the flow-control is already clear that it’s terminating:

Even the “bad case” can be quickly identified (and fixed) due to the terminating flow-control. This concept/structure “rule” also applies to a number of languages.

if (x)
    return y;
    always();

Of course, this is also why one might use a linter..

Answer

Sometimes they seem to be needed! I couldn't believe it myself, but yesterday it occurred to me in a Firebug session (recent Firefox 22.0) that

if (! my.condition.key)
    do something;

executed do something despite my.condition.key was true. Adding braces:

if (! my.condition.var) {
    do something;
}

fixed that matter. There are myriards of examples where it apparently works without the braces, but in this case it definitely didn't.

People who tend to put more than one statement on a line should very definitely always use braces, of course, because things like

if (condition)
    do something; do something else;

are difficult to find.

Answer

I would just like to note that you can also leave the curly braces off of just the else. As seen in this article by John Resig's.

if(2 == 1){
    if(1 == 2){
        console.log("We will never get here")
    }
} else 
    console.log("We will get here")
Answer

There is a way to achieve multiple line non curly braces if statements.. (Wow what english..) but it is kinda tedius:

if(true)
   funcName();
else
   return null;


function funcName(){
  //Do Stuff Here...
}
Answer

The beginning indentation level of a statement should be equal to the number of open braces above it. (excluding quoted or commented braces or ones in preprocessor directives)

Otherwise K&R would be good indentation style. To fix their style, I recommend placing short simple if statements on one line.

if (foo) bar();    // I like this. It's also consistent with Python FWIW

instead of

if (foo)
   bar();   // not so good

If I were writing an editor, I'd make its auto format button suck the bar up to the same line as foo, and I'd make it insert braces around bar if you press return before it like this:

if (foo) {
  bar();    // better
}

Then it's easy and consistent to add new statements above or below bar within the body of the if statement

if (foo) {
  bar();    // consistent
  baz();    // easy to read and maintain
}
Answer

Always found that

if(valid) return;

is easier on my eye than

if(valid) {
  return;
}

also conditional such as

(valid) ? ifTrue() : ifFalse();

are easier to read (my personal opinion) rather than

if(valid) {
  ifTrue();
} else {
  ifFalse();
}

but i guess it comes down to coding style

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.