slider
slider

Reputation: 2816

Ternary Conditional Operator for else if

I can use the ternary conditional operator for an if {} else {} statement like this: a ? x : y, or question ? answer1 : answer2.

Is it possible to use this format with an else if clause? E.g. something like:

a ? b ? x : y : z

...or is this just overkill?

Upvotes: 4

Views: 3546

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

Both x and y in a ? x : y are complete expressions, so you are allowed to put any kind of sub-expressions into them, as long as they produce results of the correct type.

However, nesting of conditional expressions quickly becomes unmanageable, so using parentheses is a very good idea:

let res = a ? (b ? x : y) : z

or

let res = a ? x : (b ? y : z)

or even

let res = a ? (b ? w : x) : (c ? y : z)

Upvotes: 7

Related Questions