Javascript one line If...else...else if statement

Sam Perlmutter picture Sam Perlmutter · Mar 13, 2015 · Viewed 171.4k times · Source

I know you can set variables with one line if/else statements by doing var variable = (condition) ? (true block) : (else block), but I was wondering if there was a way to put an else if statement in there. Any suggestions would be appreciated, thanks everyone!

Answer

Gremash picture Gremash · Mar 13, 2015

Sure, you can do nested ternary operators but they are hard to read.

var variable = (condition) ? (true block) : ((condition2) ? (true block2) : (else block2))