AJW
AJW

Reputation: 5873

javascript multiple ternary operator

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.

Upvotes: 0

Views: 1138

Answers (2)

user404
user404

Reputation: 2028

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);

Upvotes: 0

Mouser
Mouser

Reputation: 13304

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.

Upvotes: 2

Related Questions