6

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.";
};
Ghostman
  • 6,042
  • 9
  • 34
  • 53
ronniejay
  • 61
  • 1
  • 1
  • 2

4 Answers4

10

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
6

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

AhmadAssaf
  • 3,556
  • 5
  • 31
  • 42
2

You can drop curly braces for nearly all block-scoped structures (if, for, while, etc). The only exception (heh) I've ran into where this isn't the case is with try and catch.

If you don't include curly braces, only the first statement after the block will be executed.

var out = document.getElementById("out");

for (var i = 0; i <= 5; i++) out.innerHTML += i;

if (out.innerHTML === "012345") out.innerHTML += " success!";
<textarea id="out"></textarea>
Scott
  • 5,338
  • 5
  • 45
  • 70
-1

brackets are optional for if statement

Pato Loco
  • 1,205
  • 1
  • 13
  • 29