Pinkie
Pinkie

Reputation: 10256

JavaScript Conditional shortcut. More then one else if

Can we have more then one else if statement using the conditional shortcut.

var x = this.checked ? y : z;

Upvotes: 4

Views: 198

Answers (6)

Samyak Bhuta
Samyak Bhuta

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

Pete Wilson
Pete Wilson

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

niksvp
niksvp

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

Frédéric Hamidi
Frédéric Hamidi

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

Hamish
Hamish

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

Shadow Wizzard
Shadow Wizzard

Reputation: 66388

Not really, but you can have several nested statements:

var x = this.checked ? y : (some_other_condition) ? z : z2;

Upvotes: 2

Related Questions