Ternary operator with three possible conditions

Asked

Viewed 717 times

4

For a certain status, I can have 3 different stages:

  • 0 = Stopped
  • 1 = Sending
  • 2 = Delivered

Then you could have:
status = 0 or
status = 1 or
status = 2

For each stage, I need to set an icon.

If I had only two stages, being 1 or 2, the code below would be enough for me.

let status = 1;
const sendStatus = `<i class="${status < 2 ? "icon-1" : "icon-2"}"></i>`;

But since there is also stage 0, which is the stage default, how can I set an icon for status 0, unused if ?

  • Wouldn’t it be something like status < 2 ? (status == 1 ? "icon-1" : "icon-0") : "icon-2"?

  • Maybe it could be this way, but it can ? It’s a good practice ?

  • I see no problem doing that.

3 answers

8


You can use ternary operators nestled. Something like that:

function getClass(status) {
  return status === 0
    ? 'default'
    : status === 1
      ? 'icon-1'
      : 'icon-2';
}

console.log(getClass(0));
console.log(getClass(1));
console.log(getClass(2));

Note that I created a function only to demonstrate the three possible cases. You do not necessarily need to create a function to achieve these results.

However, many consider using nested ternary operators to be a bad practice, as it may impair the readability of the code. You can then use an object to map a certain key to a value. Something like this:

function getClass(status) {
  const map = {
    0: 'default',
    1: 'icon-1',
    2: 'icon-2'
  };

  return map[status];
}

console.log(getClass(0));
console.log(getClass(1));
console.log(getClass(2));

To ensure that a value is always returned from the expression, even if the object does not have the key that was accessed, you can use the logical operator OR (||):

object[key] || 'Valor padrão';

For example:

const map = {
  0: 'default',
  1: 'icon-1',
  2: 'icon-2'
};

console.log(map[3] || 'default');

Alternatively to ||, if the environment supports, the null coalescence operator (??) may be more appropriate as it would also allow the mapping of values considered falsy for ||, such as '', 0 etc..

  • 1

    Surely the last option - an associative matrix with handlers - is the most 'modern' and beautiful, in Python would also be considered the most 'pythonic''.

4

let status = 1;
const sendStatus = `<i class="${status == 0 ? 'icon-0' : status == 1 ? 'icon-1' : 'icon-2'}"></i>`;

let status = 1;
const sendStatus = `<i class="${'icon-' + status}"></i>`;

let icons = ['icon-0', 'icon-1', 'icon-2']
let status = 1;

const sendStatus = `<i class="${icons[status]}"></i>`;

Various ways to solve this.

  • The name icon-1 or icon-2 is only one example, actually icon-? It will have another name, for example, fa-check

  • It is not good practice to insert the HTML inside the JS and it is already possible to change it by the HTML itself. (This not taking React into account, here’s another story)

  • I disagree, depending on the situation, the javascript itself has the function createElement to create HTML elements dynamically

2

I could wear a suit like that:

status é diferente
de 0? (true)
   ↓
status ? status < 2 ? 'icon1' : 'icon2' : 'icon0'
         \___________________________/       ↓
                       |                 se status for
            este bloco é caso status    igual a zero (false)
             seja diferente de zero.
               Se for menor que 2,
                    então é 1

Testing:

let status = 0;
let sendStatus = `<i class="${status ? status < 2 ? 'icon1' : 'icon2' : 'icon0'}"></i>`;
console.log(sendStatus);

status = 1;
sendStatus = `<i class="${status ? status < 2 ? 'icon1' : 'icon2' : 'icon0'}"></i>`;
console.log(sendStatus);

status = 2;
sendStatus = `<i class="${status ? status < 2 ? 'icon1' : 'icon2' : 'icon0'}"></i>`;
console.log(sendStatus);

  • A doubt, this type of code is or is usually usual within programming in general?

  • Wagner, I’ve used it a few times on occasion. If it is common to be used I can not say accurately, because each programmer can have a different style of writing that thinks better. I see a lot of ordinary things around that I don’t like to use. That goes for everyone.

  • Having to believe that this is common, because I see it as the most efficient and simple way to achieve the expected result.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.