Are braces necessary in one-line statements in JavaScript?
Asked Answered
G

21

227

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.

Goosegog answered 25/1, 2011 at 18:17 Comment(5)
Note: only the first statement is assuming the scope, even if you have several statements on one line, so it is not "one line statements" but rather single statementDucharme
You may be thinking of the issue described in this answerBrabant
@Blorgbeard: no, I actually replied to that answer while ago.Goosegog
Hah, so I see. Never mind then :)Brabant
Here's your answer: medium.com/@jonathanabrams/…Dues
S
263

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!")
}
Sugared answered 25/1, 2011 at 18:18 Comment(30)
+1, informative answer. Personally though, I've never found it useful to do this "recommended" thing. I've never coded python, so I don't just insert things and expect the indentation to matter. If I add a statement, I also add braces. Always. Can't remember a single time it bit me. Not in C, not in C# not in JavaScript.Sheepshank
@Kirk: Douglas Crockford recommends it. I agree that it is a subjective personal decision but when working in a group it is easier to simply type the braces.Sugared
Maybe I should add that I've started to use braces everywhere since that's the way code is supposed to look at my workplace. And since it's "recommended", maybe it's better to practice what most people are doing rather than going your own route just because it works for you.Sheepshank
@Josh, oh, well Crockford said it. That must be the final word. ;) (just kidding) The issue is that the subjectivity of this point extends across all C-like languages, and strong opinions can be found throughout (for both positions).Parnassian
@Kirk: Agreed. I suppose that the language feature has a place, and I support a flexible syntax that allows you to personalize code. However, I do recommend you avoid it. Choice is yours. :)Sugared
@Kirk subjective until we all use his jslint.com to check our code for mistakes (or as part of the build-release rules) and get sick of the messages about it [all hail DC!]Deepseated
@Rudu: JSLint has no place in an automated build.Sugared
@Rudu: Clarifying your statement I assumed part of an automated build / release rule set.Sugared
With curly braces on a separate line I would never use them for single-statement blocks. 8 vs 4 lines in a huge difference.Scrubby
@Scrubby That's fine, it's preference.Sugared
It's preference, but there's a huge propensity for error by not including the braces. Don't underestimate human error. It's easier to identify a missing brace than it is to identify white space problems.Andersen
My personal experience shows that not placing bracers can lead to big screw-ups when working on teams.Gony
I like omitting braces, that's why I switched to CoffeeScript ;)Albinus
Seems like YUI compressor adds them around one line statements while it is supposed to save every possible byte out of JavaScript files.Mobcap
"Highly recommended" - for people who can't keep consistent indentation at least anyway :)Bladdernut
Not sure if it's been mentioned but not all blocks can do this. try...catch blocks require braces (that's true in most languages).Gillispie
I never use curly braces for a single statement. I write as little code as possible. Be a rebel. Don't use them if you don't need them ;) Most of my colleagues agree. If you need 2 or more statements, you add the braces then. Never tripped me up, Ever.Modest
Brevity begets clarity.Discomfort
It's a good practice to always use the braces {}. As @Arx said, there's a lot more room for error if you leave them out. Apple even had a bug in iOS's SSL/TLS because they didn't use bracesMaccarone
Dont forget about one liners :) if (foo === bar) return;Waist
@KirkWoll almost everything is subjective in programming. So it always comes down to best practises :)Namecalling
YAGNI concept applies?Arakawa
One line if else is a scourge. I've been debugging for hours and suffering from the fact that rampant one line if else usage has led to rampant laziness about not logging errors because it would require refactoring to add blocks. Lazy, lazy, lazy ... wasting my time and making the code nearly unreadable. Yeah ... I'm deeply annoyed :-)Caton
I heard somewhere that not using braces won't work on some browsers, But i'm not certain about it.Tolley
@mohaka I'd be interested in knowing which browsers if you find out more.Sugared
You left out semi-colons, is that OK?Subsistent
It's not always due to laziness that we resort to avoiding the braces. Often it makes the code cleaner and more readable, especially if it's just a single statement nested somewhere.Sextuplicate
For reference the Linux C style is to not add unnecessary braces.Driver
The unnecessary braces make it messier to read. And if you're not relying on a tool to do your indenting for you routinely anyway, you're already asking for trouble.Vitriolic
removing the braces is useless, it does not contribute to better code readability and at the end you will have same resultMackoff
D
116

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.

Deepseated answered 25/1, 2011 at 18:25 Comment(3)
That's why we should always use it as one-liner: if (a===true) alert(a);. Now it's clear!Schlimazel
Using curly-left-bracket and curly-right-bracket makes conditionals clear. For the dreamers among us, also referred to as the left and right flying bird.Perisarc
ALWAYS USE AUTOMATED INDENTATION, PEOPLEVitriolic
S
76

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.

Samul answered 6/1, 2013 at 12:41 Comment(4)
I always felt one should always include braces... but I'm rethinking it now. You have the airbnb style guide on your side!Wroth
Yet you forget that most code formatters change that to a 2-line format and you are back to problematic code. The vertical space argument is just silly. Readability always wins, and today's screens are huge.Caton
The 2-lines added for each bracket, to surround your one-line statements are not a big cost compared to a potential damage that can be caused by a - even very careful developer - maintaining your code. You yourself can be a great developer with a mythical skills, but you can not assume that your colleagues are. KISS, wrap things with a context and make it as easy as possible for others or you will eventually get into trouble.Intrigant
@Wroth The eslint rule to control this can be found here: eslint.org/docs/rules/curly#multi /*eslint curly: ["error", "multi"]*/Derosier
P
26

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.

Pharmaceutical answered 23/2, 2017 at 13:3 Comment(3)
well the obvious bug is the DoSomethingMore(); But there is also another bug. if a is null and b is null, you only get "error b", you never get "error a".Gospel
@Gospel 'if a is null and b is null, you only get "error b", you never get "error a".' That may be wanted, you get "error a" when a is null, but b isn't. Maybe b is more important to be not null, which is why the nested if in the else was added. :-)Confirm
> 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'. It's DEFINITELY personal preference. You didn't argue this point. You just made your personal opinion clear.Kleon
B
12

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!

Blackjack answered 11/3, 2012 at 15:2 Comment(6)
Don't you mean if, else and alert and not If, Else and Alert?Renaerenaissance
Wow, I did not know this, thank you for informing me! Seems most people leave out this important detail.Chenille
While this works in JavaScript, it's beyond me why you would ever want to do that. I am venturing a guess that the majority of developers are not aware of this (myself included prior to reading this), which I suspect would then quickly become a maintainability issue among developers. Sometimes, the most clever way is not the best.Pickled
This is horrible. If someone adds a statement and forgets to turn the semicolon into a comma on the now second to last statement in the block, you have a bug that can be really hard to spot because the comma and semicolon at the end of the line look way too similar.Jibe
I prefer a "Hemingwayian" approach: very clean. And without space between if and (, like if(true) doSomething();Coniology
If you dont want to get fired on your first day as JS developer, dont do this. You will get this denied on code reviewsMackoff
M
10

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.

Minutes answered 25/1, 2011 at 18:19 Comment(0)
T
7

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

Terriss answered 25/1, 2011 at 18:33 Comment(1)
All of those examples look horrible to me, unless the writers are temporary and paid by line or until it works.Duane
M
7

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

Marmion answered 3/4, 2018 at 6:52 Comment(0)
C
6

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

Competition answered 25/1, 2011 at 18:26 Comment(0)
J
4

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

Jhansi answered 24/8, 2019 at 2:38 Comment(0)
B
3

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.

Bibliopole answered 25/1, 2011 at 18:22 Comment(3)
That's not correct, you are missing the 'else': if(someVal) alert("True"); else alert("AlsoTrue"); would be correct. I would not use it because I like the {} for it is far better readable.Leverage
Huh? I didn't have an else statement. I was saying that without curly braces, it can lead to bugs if someone adds a new line. I think you didn't understand my point.Bibliopole
I think what he's saying is that, the 2nd line will get executed no matter what. An If statement without braces can only execute 1 line.Namecalling
R
3

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.

Robi answered 22/1, 2015 at 18:37 Comment(0)
C
2

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
Celebration answered 9/9, 2015 at 13:15 Comment(0)
L
2

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();
Lozar answered 25/6, 2018 at 7:44 Comment(0)
I
1

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;
Imco answered 26/2, 2018 at 18:49 Comment(0)
D
0

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")
Dense answered 5/3, 2015 at 14:47 Comment(3)
The [Qt braces style][1] requires blocks on both sides of an else to match brace usage -- this example would require the braces on the else block in order to pass a code review. [1]: wiki.qt.io/Qt_Coding_Style#BracesFellows
Why the downvote? The statement above is 100% accurate.Dense
I did not downvote your answer. You are correct: what you stated is 100% correct and your answer does not deserve the downvote.Fellows
F
0

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
}
Fanechka answered 10/3, 2018 at 18:17 Comment(0)
L
0

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.

Lasso answered 19/8, 2020 at 1:48 Comment(0)
C
0

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.

Cattier answered 17/10, 2020 at 23:53 Comment(0)
C
-1

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.

Clubbable answered 13/8, 2013 at 15:36 Comment(2)
I am curious in what scenario the lack of braces made the if condition true, can you recall or give a real example of it?Dufy
The conditional expression is always evaluated before the statement. I'm also very curious to see a real example of this because it would represent a bug in the interpreter.Punak
O
-1

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...
}
Outlet answered 24/4, 2016 at 23:56 Comment(1)
You don't have to have so many new lines when omitting curly braces. The above can also be written on two lines as: if (true) funcName() and else return nullUnscratched

© 2022 - 2024 — McMap. All rights reserved.