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..
Wouldn’t it be something like
status < 2 ? (status == 1 ? "icon-1" : "icon-0") : "icon-2"
?– tvdias
Maybe it could be this way, but it can ? It’s a good practice ?
– Wagner Fillio
I see no problem doing that.
– tvdias