Sometimes it's really hard to grasp the idea of nested ternary in JavaScript, so I decided to present the simplest way of it, because I also struggled in the past when I just was too lazy to use if statements and wanted something handy and short. So this is it!
Suppose we have this task from codewars.com. Here what it says:
Given a month as an integer from 1 to 12, return to which quarter of the year it belongs as an integer number.
For example: month 2 (February), is part of the first quarter; month 6 (June), is part of the second quarter; and month 11 (November), is part of the fourth quarter.
Let's implement it in ternary:
First we are checking whether month is less than 4:
const quarterOf = (month) => {
return month < 4 ? 1
}
Then like always in ternary we are adding a colon
const quarterOf = (month) => {
return month < 4 ? 1 :
But instead of just adding the value in case of false we are adding the next condition which works just fine:
const quarterOf = (month) => {
return month < 4 ? 1 :
month < 7 ? 2 :
And we can do it many times:
const quarterOf = (month) => {
return month < 4 ? 1 :
month < 7 ? 2 :
month < 10 ? 3 :
4;
}
And at the end we put the value like in else case.
Top comments (1)
I don't like the idea of adding more ternary conditions into another. IMO this decrease a lot the readability of the code