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.
let inputOneAns = inputOne === 'Yes' ? '517' : inputOne === 'No' ? '518' : '';
but just don't. It's ugly and anif
/else
is far more readable. And if your colleagues know where you live, it's a risk you don't want to take... – Beaneryvar choices = {Yes: 517, No: 518}; var inputOneAns = inputOne in choices ? choices[inputOne] : ""
orinputOneAns = choices[inputOne] || ""
– Homozygous