Reputation: 31
Someone asked me this question in a workshop and about what are some alternative to the if-else
statement in JavaScript except from switch
. Is the conditional operator just a shorthand for if-else
?
Upvotes: 2
Views: 2291
Reputation: 215029
JS is a "phrasal" programming language and strictly separates between expressions (values and operators) and statements. ?
is an operator and can be used within an expression:
a = x ? y : z
while if
cannot, because it's a statement:
a = if (x) ... // syntax error
On the other hand, every expression is also a statement, when used in an appropriate context:
while (1)
a = x ? y : z;
so it's fair to say that ?
is "broader" than if
because it can be used in both contexts. Which of course doesn't mean it should (rather not).
If you're interested in other ways to express conditional logic, you can do that with boolean operators:
a && do_something() // "if a do_something()"
b || do_something() // "if not b do_something()"
although such uses are mostly considered bad style.
Upvotes: 5
Reputation: 24280
It is somewhat shorthand, but only in case of returning / obtaining a value or object from two possible expressions.
Examples:
// inside a function
if (condition) { return X; } else { return Y; }
// Functionally equivalent to
return condition ? X : Y;
var tmp;
if (condition) { tmp = GetFoo(123); } else { tmp = GetBar(456); }
DoSomething(tmp);
// Functionally equivalent to
DoSomething(condition ? GetFoo(123) : GetBar(456));
If there are no return values, there is still an equivalency but people might scream at you for doing this:
if (condition) { A(); } else { B(); }
// *shudder*
condition ? A() : B();
And the following are impossible or at least hard to change into ?:
:
if (condition) { A(); return true; } else { B(); return false; }
// Reason: code blocks contain multiple statements
if (condition) { tmp = GetFoo(123); }
// Reason: no "else"-block (or you need to construct/invent one)
Upvotes: 0