Possible Duplicate:
Are curly braces necessary in one line statements in JavaScript?
I am almost positive of this, but I want to make sure to avoid faulty code. In JavaScript do single if statements need curly braces?
if(foo)
bar;
Is this OK?
4 Answers 4
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.
The following will work
if(foo)
Dance with me;
else
Sing with me;
The following will NOT work the way you want it to work.
if(foo)
Dance with me;
Sing with me;
else
Sing with me;
You don't know anything;
But if the above is corrected as in the below given way, then it works for you:
if(foo){
Dance with me;
Sing with me;
}else{
Sing with me;
You don't know anything;
}
1 Comment
if statement, my options are 1) break the code or 2) go back to the "less pretty" way, and in the process create an ugly diff by modifying multiple lines when I just want to add one. It seems like using curlies to start with is the most sensible option.While it's syntactically okay to omit them, you shouldn't. The one case where ambiguity strikes hard is
if (false)
if (true) foo();
else
bar();
This will run neither foo nor bar since the else belongs to the second if statement. No problem if braces are used:
if (false) {
if (true) { foo(); }
} else {
bar();
}
5 Comments
if (...) per line (which one should do anyway, following the argument of code readability), it's never going to be a problem, because one would automatically use braces for multiple lines.Yes it is allowed. It is also discussed before:
But it should be avoided:
Comments
Yes, it's syntactically valid. But it is considered bad style.
If you wrote it on a single line, you could argue that there are situations where it's okay, because it is unambiguous.
if (foo) bar;
In most cases though, using curly brackets adds to code clarity, which is a good thing. Code is more often read than written, and it should be as unambiguous as possible.
Also, if you at some point need to add a second statement, you will most definitely need curlies anyway.
4 Comments
if followed by ( followed by an expression followed by ) followed by a statement, which { statements }; is a statement, aswell as bar; in your example. It is unambiguous, you just need to know what a statement is...