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 inputOneAns
whether 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.
We can nest ternary operators to test multiple conditions.
You can nest one ternary operator as an expression inside another ternary operator to work as a Nested ternary operator in JavaScript.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With