suhail c suhail c - 18 days ago 6
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

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

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

console.log(b);


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.

Comments