Multiple Ternary Operators Multiple Ternary Operators javascript javascript

Multiple Ternary Operators


The syntax would be:

var icon = (area == 1) ? icon1 : (area == 2) ? icon2 : icon0;

But this is starting to get complicated. You may well be better off just creating a function to do this work instead:

var icon = getIcon(area);function getIcon(area) {  if (area == 1) {     return icon1;   } else if (area == 2) {     return icon2;   }  return icon0;}


How about:

var icon = [ icon0, icon1, icon2 ][area];


For anyone that's confused about the multiple ternary syntax (like I was), it goes like this:

var yourVar = condition1 ? someValue            : condition2 ? anotherValue            : defaultValue;

You can add as many conditions as you like.

You can read up further on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator