Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are braces necessary in one-line statements in JavaScript?

Tags:

javascript

People also ask

Do JavaScript if statements need brackets?

Yes, it works, but only up to a single line just after an 'if' or 'else' statement. If multiple lines are required to be used then curly braces are necessary.

Is it compulsory to put braces for single statement with for loop?

They are optional. That is just how it is. If you don't use braces to group multiple statements into one, then only the first statement following the for or if preamble is considered part of that construct.

Can we use if statement without brackets?

Conclusion. So as you can see for multiple statement if we don't use curly braces for multiple statement then statement within "if" condition get executed wrong. It is okay to use without curly braces with one statement.

Is it necessary to use curly braces after the for statement?

If the number of statements following the for/if is single you don't have to use curly braces. But if the number of statements is more than one, then you need to use curly braces.


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

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.


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.


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.


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!


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.


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