suhail c suhail c - 1 year ago 68
Javascript Question

Using multiple conditions in ? : statements in javascript

In need to check three conditions and assign a value to a variable according the condition.

if(a =="z1"){
b = "one";
} else if(a =="z2"){
b = "two";
} else if(a =="z3"){
b = "three";

Is it possible to do it in JavaScript using ? : statement to make it as a single line code

Answer Source

Yes, you can use convert it to Conditional(ternary) operator.

var a = "z3";
var b = a == "z1" ? "one" : a == "z2" ? "two" : a == "z3" ? "three" : "" ;


FYI : For a better readability, I would suggest using if...else statement or use switch statement . Although you need to use parenthesis for nested ternary operator for avoiding problems in case complex operations.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download