183

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.

João Pimentel Ferreira
  • 9,166
  • 6
  • 52
  • 67
Tower
  • 87,855
  • 117
  • 329
  • 496

21 Answers21

223

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!")
}
Josh K
  • 26,152
  • 19
  • 79
  • 130
  • 33
    +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. – Jakob Jan 25 '11 at 18:21
  • 17
    @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. – Josh K Jan 25 '11 at 18:22
  • 2
    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. – Jakob Jan 25 '11 at 18:24
  • 10
    @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). – Kirk Woll Jan 25 '11 at 18:27
  • 1
    @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. :) – Josh K Jan 25 '11 at 18:31
  • 1
    @Kirk subjective until we all use his http://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!] – Rudu Jan 25 '11 at 18:33
  • @Rudu: JSLint has no place in an automated build. – Josh K Jan 25 '11 at 18:46
  • @Rudu: Clarifying your statement I assumed part of an automated build / release rule set. – Josh K Jan 25 '11 at 19:03
  • 2
    With curly braces on a separate line I would never use them for single-statement blocks. 8 vs 4 lines in a huge difference. – ThiefMaster May 22 '12 at 18:41
  • @ThiefMaster That's fine, it's preference. – Josh K May 24 '12 at 22:09
  • 2
    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. – arxpoetica Jul 31 '12 at 16:26
  • 11
    My personal experience shows that not placing bracers can lead to big screw-ups when working on teams. – Sirs Oct 03 '12 at 11:50
  • I like omitting braces, that's why I switched to CoffeeScript ;) – Pierre Nov 09 '12 at 18:18
  • Seems like YUI compressor _adds_ them around one line statements while it is supposed to save every possible byte out of JavaScript files. – Salman A Jan 06 '13 at 20:33
  • 2
    "Highly recommended" - for people who can't keep consistent indentation at least anyway :) – Mark K Cowan Sep 03 '13 at 12:33
  • 1
    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). – Qix - MONICA WAS MISTREATED May 31 '14 at 19:37
  • 2
    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. – Justin Jul 02 '14 at 05:12
  • Brevity begets clarity. – caleb Jul 08 '14 at 16:08
  • 4
    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](https://www.imperialviolet.org/2014/02/22/applebug.html) in iOS's SSL/TLS because they didn't use braces – Keenan Lidral-Porter Jan 06 '15 at 19:56
  • 1
    Dont forget about one liners :) if (foo === bar) return; – Tony Gustafsson Nov 27 '15 at 16:22
  • @KirkWoll almost everything is subjective in programming. So it always comes down to best practises :) – PostCodeism Jun 17 '16 at 16:33
  • YAGNI concept applies? – Chalky Oct 04 '16 at 09:21
  • 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 :-) – Kim Nov 23 '17 at 01:06
  • I heard somewhere that not using braces won't work on some browsers, But i'm not certain about it. – Heysem Katibi Jan 23 '18 at 15:34
  • @mohaka I'd be interested in knowing which browsers if you find out more. – Josh K May 28 '18 at 00:18
  • You left out semi-colons, is that OK? – Yan King Yin Apr 19 '20 at 18:49
  • 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. – Jason210 Nov 11 '20 at 14:32
  • For reference the Linux C style is to **not** add unnecessary braces. – FelipeC Mar 03 '21 at 00:27
97

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.

Lauren Van Sloun
  • 1,070
  • 5
  • 17
  • 20
Rudu
  • 14,886
  • 3
  • 43
  • 62
67

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.

peawormsworth
  • 1,000
  • 8
  • 8
  • 2
    I always felt one should always include braces... but I'm rethinking it now. You have the [airbnb](https://github.com/airbnb/javascript#blocks) style guide on your side! – senderle Sep 10 '15 at 18:35
  • 1
    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. – Kim Nov 23 '17 at 01:11
  • 1
    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. – Maciej Tokarz Jan 24 '18 at 11:49
  • @senderle The eslint rule to control this can be found here: https://eslint.org/docs/rules/curly#multi `/*eslint curly: ["error", "multi"]*/` – silkfire Dec 11 '19 at 12:22
19

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.

Caner
  • 49,709
  • 33
  • 153
  • 169
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!

william malo
  • 2,344
  • 2
  • 16
  • 18
  • 2
    Don't you mean `if`, `else` and `alert` and not `If`, `Else` and `Alert`? – Anish Gupta May 19 '12 at 10:34
  • Wow, I did not know this, thank you for informing me! Seems most people leave out this important detail. – Hendeca May 29 '14 at 17:19
  • 14
    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. – Simon Oct 07 '14 at 15:22
  • 14
    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. – Ingo Bürk Jan 25 '15 at 08:53
  • 1
    I prefer a ["Hemingwayian" approach](https://www.nostarch.com/hemingwayjs): very clean. And without space between `if` and `(`, like `if(true) doSomething();` – victorf Aug 17 '15 at 14:28
8

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.

Yahel
  • 8,314
  • 2
  • 22
  • 30
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 (?)

Chris Lercher
  • 36,020
  • 19
  • 96
  • 128
6

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
pault
  • 61
  • 3
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..

user2864740
  • 54,112
  • 10
  • 112
  • 187
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.

B.F.
  • 445
  • 6
  • 8
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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Amir Raminfar
  • 32,592
  • 7
  • 83
  • 119
  • 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. – Gerrit B Aug 13 '15 at 21:21
  • 2
    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. – Amir Raminfar Aug 14 '15 at 22:00
  • 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. – PostCodeism Jun 17 '16 at 16:35
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
kamayd
  • 380
  • 5
  • 9
2

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

Yogi
  • 185
  • 1
  • 4
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();
Alee
  • 632
  • 7
  • 17
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;
Gabriel I.
  • 113
  • 12
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")
Johnston
  • 18,560
  • 12
  • 64
  • 107
  • 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]: https://wiki.qt.io/Qt_Coding_Style#Braces – pixelgrease Jun 23 '15 at 17:50
  • Why the downvote? The statement above is 100% accurate. – Johnston Jun 03 '20 at 21:07
  • I did not downvote your answer. You are correct: what you stated is 100% correct and your answer does not deserve the downvote. – pixelgrease Oct 23 '20 at 18:18
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
}
Toku
  • 1
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.

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.

BKSpurgeon
  • 24,945
  • 9
  • 86
  • 68
-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.

Tobias
  • 2,249
  • 3
  • 21
  • 37
  • 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? – gitsitgo Jul 10 '14 at 15:53
  • 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. – Semicolon Apr 12 '15 at 20:13
-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...
}
amanuel2
  • 4,268
  • 2
  • 29
  • 61
  • 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 null` – phobos Sep 08 '16 at 12:30