JS Ternary functions with multiple conditions?

Viewed 68983

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.

9 Answers

Yes, you can use multiple condition in Ternary Operator. Hope this will help you.

var x=20;
var y = x<13 ? "Child" : x<20 ? "Teenage" : x<30 ? "Twenties" : "Old people";
console.log(y);

The most elegant and clean way is to take advantage of Object literals:

const Switch = (str) => ({
  "Yes": "517",
  "No": "518",
})[str] || '';

console.log(Switch("Yes")); // 517
console.log(Switch("No"));  // 518
console.log(Switch("Non matching value")); // Empty

This has the advantage of being both readable and flexible.

Unfortunately JavaScript does not provide a super terse and readable way to do this. Personally I would just use some single-line if statements like this:

var inputOneAns;
if (inputOne === 'Yes') inputOneAns = '517';
if (inputOne === 'No') inputOneAns = '518';
else inputOneAns = '';

Which can be even cleaner if you abstract it into a function (note: no need for else in this case):

function getInputOneAns(inputOne) {
    if (inputOne === 'Yes') return '517';
    if (inputOne === 'No') return '518';
    return '';
}

Personally, I don't really like switch statements for this for two reasons: firstly those extra break statements bloating the code, and secondly, switch statements are very limiting - you can only do simple equality checks, and only against a single variable. Besides, in the case that you know you will be always checking a single string I would favour a simple map object:

var map = { 'Yes': '517', 'No': '518' };
var inputOneAns = map[inputOne] || '';

Yes, and it does provide a cleaner code than switch statement.. with all the breaks..

inputOne == "Yes" ? "517" :
inputOne == "No" ? "518" : inputOneAns = "";
Related