Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Ternary functions with multiple conditions?

I have been using a ternary operator in JavaScript to modify the value of an object based on user input. I have the following code, which runs as it should:

var inputOneAns = inputOne == "Yes" ? "517" : "518"; 

As you can see, I am assigning a numeric string value to inputOneAnswhether a user has inputed "Yes" or "No". However, there may be a case that a user has not selected a value (as it is not required). If this input was left blank, I would like to assign an empty string "" to inputOneAns. Is there a wayf or me to embed an ternary operator inside of another ternary operator? To help clarify, here is the same function that I want to accompolish with my ternary function but with if else statements?

if (inputOne == "Yes"){     var inputOneAns = "517" }else if (inputOne == "No"{     var inputOneAns = "518" }else{     var inputOneAns = "" } 

Is it possible to include multiple expressions into a ternary function? Is there a better way to accomplish what I am looking for? Thanks for the tips in advance.

like image 550
user7366442 Avatar asked Jul 10 '17 22:07

user7366442


People also ask

Can we use multiple conditions in ternary operator JS?

We can nest ternary operators to test multiple conditions.

Can we use nested ternary operator in JavaScript?

You can nest one ternary operator as an expression inside another ternary operator to work as a Nested ternary operator in JavaScript.


Video Answer


1 Answers

Yes you can go wild nesting ternaries. I find this version to be fairly readable:

var foo = (   bar === 'a' ? 1 : // if    bar === 'b' ? 2 : // else if    bar === 'c' ? 3 : // else if   null // else  ); 

but that's not a widely shared opinion, and you should probably stick to if/else or switch when working on a team.

like image 65
Damon Avatar answered Sep 20 '22 17:09

Damon