Nesting a Tenary Operation is like having multiple if/else statements.
I talked about a Tenary Operator in one of my previous posts and today, we will talk about how you can Nest a Tenary Operation.
Considering the Block Below
var num = 200;
if (num < 100) {
console.log('Number less than 100');
}else if(num > 100) {
console.log('Number is greater than 100');
}else {
console.log('Number is not an Integer');
}
If you run this code, you will get the output
Now this code has at least 3 blocks. How do we make it a Nested Tenary Operation?
Well, it's easy!
Using the Syntax below, you can create a Nested Tenary Operation.
(condition) ? (action if true) : (action if false)
So this is more like saying
(if statement) { (action if true) else { (action if false) }
Converting the blocks to a Nested Tenary Operation would be
var num = 200;
(num < 100) ? console.log('Number less than 100') :
(num > 100) ? console.log('Number is greater than 100') :
console.log('Number is not an Integer')
And this is the output
You can have more blocks nested within just like using if, elseif, 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 Tenary Operators is that; you don't have to worry about the elseif 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 Tenary Operation.
Let me know in the comment section below if you found this Post Helpful.
Thank You!