0

I currently have some JS, which checks the user agent (iOs or not) and sets some variables according to the result. So, I have something like:

var isOnIOS = navigator.userAgent.match(/iPad/i)|| navigator.userAgent.match(/iPhone/i);
var eventName_unload = isOnIOS ? "something_if_true" : "something_if_false";
var eventName_load = isOnIOS ? "something0_if_true" : "something0_if_false";

Now, I have to do another check, for Samsung briswer like so:

var isOnSamsung=navigator.userAgent.match(/SAMSUNG|Samsung|SGH-[I|N|T]|GT-[I|N]|SM-[A|N|P|T|Z]|SHV-E|SCH-[I|J|R|S]|SPH-L/i)

and I would like to create a multiple ternary here to something like so:

var eventName_unload = isOnIOS ? "something_if_true" : "something_if_false" :: isOnSamsung ? "somethingX_if_true" : "somethingX_if_false";

Obviously, the above is not correct (just pseudo-code), and I was wondering what is the correct syntax to invoke multiple ternary operator to achieve this.

thank you.

AJW
  • 5,569
  • 10
  • 44
  • 57
  • Use another ternary inside the value of ternary with parentheses,.eg, `query ? ( another query ? value1 : value2 ) : value3` – vaku Jan 12 '20 at 11:52
  • Bear in mind that nested ternary conditions = loss of readability. – Mitya Jan 12 '20 at 11:53
  • 1
    Does this answer your question? [Multiple Ternary Operators](https://stackoverflow.com/questions/7757549/multiple-ternary-operators) – Mouser Jan 12 '20 at 12:03

2 Answers2

2

You do it like this

const eventName_unload = isOnIOS ? "something_if_true" : 
                         isOnSamsung ? "somethingX_if_true" : "something_if_false";

Unless you want to specifically do something else when not Samsung or not IOS. But this is how you "stack" multiple ternary operators.

Mouser
  • 13,132
  • 3
  • 28
  • 54
  • I do want to do something (default) if something is not iOS or isOnSumsung - I just found this: https://stackoverflow.com/questions/7757549/multiple-ternary-operators and Adam's solution here seems to accept a default value - is this not correct? – AJW Jan 12 '20 at 11:58
0

I think you can do this way too:

const eventName_unload= condition ? ("if-true"? "true result": "false result"):"first false result";

Hence you can chain further conditions too!
Example

var a=2;
var b= a >2 ?( a<5 ? "within 2-5":"gt 5"):"000";
console.log(b);
user404
  • 1,934
  • 1
  • 16
  • 32