JS Ternary functions with multiple conditions?
Asked Answered
A

10

44

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.

Argumentum answered 10/7, 2017 at 22:11 Comment(3)
You can nest ternary operators but it usually isn't very clearMiffy
let inputOneAns = inputOne === 'Yes' ? '517' : inputOne === 'No' ? '518' : ''; but just don't. It's ugly and an if/else is far more readable. And if your colleagues know where you live, it's a risk you don't want to take...Beanery
var choices = {Yes: 517, No: 518}; var inputOneAns = inputOne in choices ? choices[inputOne] : "" or inputOneAns = choices[inputOne] || ""Homozygous
E
87

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.

Eogene answered 10/7, 2017 at 22:41 Comment(5)
very helpful, can we write multi-line statement using this syntax?Lyman
yes, I wouldn't overdo it but the reason I like it is that ternary is an expression rather than a statement, so you can assign a const based on multiple conditions rather than having to reassign a variable.Eogene
Thanks Damon, It's really helpfulLyman
this is nice and elegant solution. thank you.Bucher
You just saved me from a crazy headache... Thank you.Ostrich
S
16

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);
Sublease answered 16/6, 2020 at 19:15 Comment(0)
M
8

A switch statement is likely the best choice in a situation like this.

let inputOneAns;
switch(inputOne) {
  case "Yes":
   inputOneAns = "517";
   break;
  case "No":
   inputOneNas = "518";
   break;
  default:
   inputOneNas = "";
}

If you could do ternary operations beyond 2 conditions, they would become incredibly messy. You can put conditions together, but I've no idea why you would want that - that would be incredibly messy.

Mahlstick answered 10/7, 2017 at 22:16 Comment(0)
R
6

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.

Riches answered 30/5, 2019 at 12:52 Comment(0)
L
2

Yeh you can chain them together much like using an else if statement, but it can sometimes be a bit hard to read though, so I tend to split mine over multiple lines.

var inputOneAns = inputOne == 'Yes' ? '517' :
  inputOne == 'No' ? '518' : '';

However in this case I would suggest a switch statement seeing as you're comparing the same value for every case.

Luau answered 10/7, 2017 at 22:17 Comment(0)
E
2
var r = inputOne == "" ? "" : ( 
inputOne == "Yes" ? "517" : "518");
Eburnation answered 10/7, 2017 at 22:52 Comment(0)
M
1

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] || '';
Mehalek answered 30/5, 2018 at 13:40 Comment(0)
L
1

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

inputOne == "Yes" ? "517" :
inputOne == "No" ? "518" : inputOneAns = "";
Logsdon answered 23/5, 2020 at 2:4 Comment(0)
R
0

Seems like a classic use for a switch statement:

let inputOneAns = '';
switch(inputOne) {
  case 'Yes':
    inputOneAns = "517";
    break;
  case 'No': 
    inputOneAns = "518";
    break;
  default:
    inputOneAns = "";
}
  • note you don't actually need the default case, but I find it makes things more readable.
Railing answered 10/7, 2017 at 22:19 Comment(0)
A
0

just trust your intuition! here is what you can find in freecodecamp website as well:

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

cheers!

Anhedral answered 20/5 at 10:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.