Reputation: 10256
Can we have more then one else if statement using the conditional shortcut.
var x = this.checked ? y : z;
Upvotes: 4
Views: 198
Reputation: 1254
It is quite possible. In programming it is called nesting.Consider this example.
hasMac = false;
hasLinux = false;
var x = hasMac ? "Mac User" : hasLinux ? "Linux user" : "User OS Unknown";
// x will be "User OS Unknown"
hasMac = false;
hasLinux = true;
var x = hasMac ? "Mac User" : hasLinux ? "Linux user" : "User OS Unknown";
// x will be "Linux user"
hasMac = true;
hasLinux = true; // or false, won't matter
var x = hasMac ? "Mac User" : hasLinux ? "Linux user" : "User OS Unknown";
// x will be "Mac user"
Upvotes: 1
Reputation: 8694
If you mean like:
var x = this.checked ? y : z : a;
The answer is no. But you can have a production like:
var x = this.checked ? y : ( z > 1 ? z : a );
Upvotes: 1
Reputation: 5563
do u mean else if
?
if so then you can go like
var x = this.checked ? y : this.elseifcheck ? z : a;
Upvotes: 1
Reputation: 263047
You can abuse the comma operator, since it evaluates both its operands and returns the second one:
var x = this.checked ? y : doSomething(), doSomethingElse(), z;
However, that makes the code less readable (and maintainable) than the corresponding if
statement:
var x;
if (this.checked) {
x = y;
} else {
doSomething();
doSomethingElse();
x = z;
}
So I would recommend using an if
statement in your case.
Upvotes: 5
Reputation: 23346
No, a ternary operator returns one of two expressions based on a boolean expression.
You can nest them, if you really want to, but it's confusing and hard to read:
var x = a ? b ? c : d : e
Upvotes: 4
Reputation: 66388
Not really, but you can have several nested statements:
var x = this.checked ? y : (some_other_condition) ? z : z2;
Upvotes: 2