5

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 Commented Nov 17, 2016 at 5:35
  • b=['one','two','three'][a[1]-1] Commented Nov 17, 2016 at 11:14

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

6 Comments

But you should not!
@Rayon : why not?
1) Unnecessary 2) Not-Readable 3) No advantage over conventional if-else condition...
@Rayon : for reducing number of char it's helpfull
It is one step closer to minification. :P
|
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.

Comments

1

You can do this things:

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

Comments

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 ) ) );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.