Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 469
rubixibuc Avatar asked Aug 19 '11 06:08

rubixibuc


People also ask

Do you need curly braces for if statement?

If the true or false clause of an if statement has only one statement, you do not need to use braces (also called "curly brackets"). This braceless style is dangerous, and most style guides recommend always using them.

Can you have multiple if statements in JavaScript?

You can have as many else if statements as necessary. In the case of many else if statements, the switch statement might be preferred for readability. As an example of multiple else if statements, we can create a grading app that will output a letter grade based on a score out of 100.

What happens if you do not follow an IF () statement with opening and closing curly braces?

In C# curly braces are optional, but only for the first line of code. Meaning that if the statement does not have braces, only the line of code right after the if condition (the statement body) will be executed. Everything else falls outside the statement body and therefore will not be executed.


1 Answers

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;  } 
like image 115
OM The Eternity Avatar answered Sep 23 '22 02:09

OM The Eternity