Do 'if' statements in JavaScript require curly braces? [duplicate]

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?


Solution 1:

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

Solution 2:

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

Solution 3:

Yes it is allowed. It is also discussed before:

  • Are curly braces necessary in one-line statements in JavaScript?

But it should be avoided:

  • Single statement if block - braces or no?

Solution 4:

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.