Nesting a Ternary Operation is like having multiple if/else statements.
I talked about a Ternary Operator in one of my previous posts and today, we will talk about how you can nest a Ternary Operation.
Considering the Block Below
If you run this code, you will get the output
Now, this code has at least 3 blocks. How do we make it a Ternary block?
Well, it’s easy!
Using the Syntax below, you can create a Nested Ternary Operation.
So this is more like saying.
Converting the if statement above to a Nested Ternary block would be
And this is the output
You can have more blocks nested within just like using if, else if, else statements. All you have to do is to repeat the (:) colon mark and the next block comes after it.
One good thing about Nesting Ternary Operators is that; you don’t have to worry about the else if or else keywords because it has already been taken care of by the (:) colon mark.
So you could save a lot of time trying to write a Nested if statement just by using a Nested Ternary Operation.
Let me know in the comment section below if you found this Post Helpful.
Thank You!