4

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

2
  • 1
    Java !== JavaScript
    – Rayon
    Commented Nov 17, 2016 at 5:35
  • b=['one','two','three'][a[1]-1] Commented Nov 17, 2016 at 11:14

4 Answers 4

7

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.

6
  • 1
    But you should not!
    – Rayon
    Commented Nov 17, 2016 at 5:33
  • @Rayon : why not? Commented Nov 17, 2016 at 5:36
  • 1) Unnecessary 2) Not-Readable 3) No advantage over conventional if-else condition...
    – Rayon
    Commented Nov 17, 2016 at 5:40
  • @Rayon : for reducing number of char it's helpfull Commented Nov 17, 2016 at 5:42
  • It is one step closer to minification. :P
    – zer00ne
    Commented Nov 17, 2016 at 5:43
1
var b = (a =="z1") ? "one" : ((a =="z2") ?"two":(a =="z3")?"three":null);

Don't forget that it's tough to read to read this quickly. It's quite ok to use for one if else block.

1

You can do this things:

b=( a=="z1"?"one":(a =="z2"? "two":(a =="z3"?"three":undefined)))

1
var b = a == "z1" ? "one" : ( a == "z2" ? "two" : ( a == "z3" ? "three" : undefined ) ) ;

a = "z1"

alert(a == "z1" ? "one" : ( a == "z2" ? "two" : ( a == "z3" ? "three" : undefined ) ) );

a = "z2"

alert(a == "z1" ? "one" : ( a == "z2" ? "two" : ( a == "z3" ? "three" : undefined ) ) );

a = "z3"

alert(a == "z1" ? "one" : ( a == "z2" ? "two" : ( a == "z3" ? "three" : undefined ) ) );

a = "z4"

alert(a == "z1" ? "one" : ( a == "z2" ? "two" : ( a == "z3" ? "three" : undefined ) ) );

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.