Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If/else statement with no curly brackets javascript? [duplicate]

I've searched and I can't find a question already like this. However, why does this code work?

    this.askTeller = function(pass) {
     if (pass == 1234) return bankBalance;
     else return "Wrong password.";
   };

Shouldn't it be like

this.askTeller = function(pass) {
if (pass == 1234) {
return bankBalance;
}
else {
return "Wrong password.";
};
like image 869
ronniejay Avatar asked Dec 05 '22 22:12

ronniejay


2 Answers

Shouldn't it be like

Arguably, it should be:

this.askTeller = function(pass) {
  if (pass == 1234) return bankBalance;
  return "Wrong password.";
};

or

this.askTeller = function(pass) {
  return pass == 1234 ? bankBalance : "Wrong password.";
};

E.g., there's no point to the else at all.

But getting to your point about {}: They're optional. Control-flow structures like if (and while, and for, etc.) are connected to the one statement that follows them; if you want to have them connected to more than one statement, you use the block statement ({...}) to do that.

Many, many, many people always use the block statement even when they could get away with not using it, both for clarity and to make it easier to add a second thing into the block.

like image 175
T.J. Crowder Avatar answered Dec 08 '22 11:12

T.J. Crowder


in Javascript the curly brackets are optional for if/else when you have only one statement after to execute. Note that if you will execute multiple stuff after then you will need to include the {/} or only the first statement will be applied to the condition

like image 26
AhmadAssaf Avatar answered Dec 08 '22 13:12

AhmadAssaf