Are braces necessary in one-line statements in JavaScript?

Javascript

Javascript Problem Overview


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.

Javascript Solutions


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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

Technically no but very recommended!!!

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.

Solution 5 - Javascript

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!

Solution 6 - Javascript

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.

Solution 7 - Javascript

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 (?)

Solution 8 - Javascript

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

Solution 9 - Javascript

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..

Solution 10 - Javascript

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.

Solution 11 - Javascript

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.

Solution 12 - Javascript

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

Solution 13 - Javascript

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

Solution 14 - Javascript

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();

Solution 15 - Javascript

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;

Solution 16 - Javascript

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")

Solution 17 - Javascript

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
}

Solution 18 - Javascript

No, curly braces are not necessary, However, one very important reason to use the curly brace syntax is that, without it, there are several debuggers that will not stop on the line inside the if statement. So it may be difficult to know whether the code inside the if statement ran without altering the code (some kind of logging/output statements). This is particularly a problem when using commas to add multiple lines of execution. Without adding specific logging, it may be difficult to see what actually ran, or where a particular problem is. My advice is to always use curly braces.

Solution 19 - Javascript

Braces are not necessary.....but add them anyway^

....why should you add braces in if statements if they are not necessary? Because there's a chance that it could cause confusion. If you're dealing with a project with multiple people, from different frameworks and languages, being explicit reduces the chances of errors cropping up by folks misreading each other's code. Coding is hard enough as it is without introducing confusion. But if you are the sole developer, and you prefer that coding style, then by all means, it is perfectly valid syntax.

As a general philosophy: avoid writing code, but if you have to write it, then make it unambiguous.

if (true){console.log("always runs");}

if (true) console.log("always runs too, but what is to be gained from the ambiguity?");
    console.log("this always runs even though it is indented, but would you expect it to?")

^ Disclaimer: This is a personal opinion - opinions may vary. Please consult your CTO for personalized coding advice. If coding headaches persist, please consult a physician.

Solution 20 - Javascript

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.

Solution 21 - Javascript

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...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTowerView Question on Stackoverflow
Solution 1 - JavascriptJosh KView Answer on Stackoverflow
Solution 2 - JavascriptRuduView Answer on Stackoverflow
Solution 3 - JavascriptpeawormsworthView Answer on Stackoverflow
Solution 4 - JavascriptCanerView Answer on Stackoverflow
Solution 5 - Javascriptwilliam maloView Answer on Stackoverflow
Solution 6 - JavascriptYahelView Answer on Stackoverflow
Solution 7 - JavascriptChris LercherView Answer on Stackoverflow
Solution 8 - JavascriptpaultView Answer on Stackoverflow
Solution 9 - Javascriptuser2864740View Answer on Stackoverflow
Solution 10 - JavascriptAmir RaminfarView Answer on Stackoverflow
Solution 11 - JavascriptB.F.View Answer on Stackoverflow
Solution 12 - JavascriptYogi View Answer on Stackoverflow
Solution 13 - JavascriptkamaydView Answer on Stackoverflow
Solution 14 - JavascriptAleeView Answer on Stackoverflow
Solution 15 - JavascriptGabriel I.View Answer on Stackoverflow
Solution 16 - JavascriptJohnstonView Answer on Stackoverflow
Solution 17 - JavascriptTokuView Answer on Stackoverflow
Solution 18 - JavascriptCurtis BlackView Answer on Stackoverflow
Solution 19 - JavascriptBenKoshyView Answer on Stackoverflow
Solution 20 - JavascriptTobiasView Answer on Stackoverflow
Solution 21 - Javascriptamanuel2View Answer on Stackoverflow