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.";
};
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With