Execute Multiple Actions in A Ternary Block
I’ve written quite a few tutorials on Ternary Operators about how you can initialize and use them, how you can nest more blocks, and in this tutorial, I will show you how you can execute multiple actions in a ternary block.
I will combine the lessons from the previous tutorials with this tutorial to create an advanced ternary block.
SYNTAX AND USAGE
Now we have a variable (x) with a value of 20 ;
If we run the code, we will get the output x is 20.
That’s how you use a Tenary operator.
Nesting Ternary Blocks
We can nest a ternary block in order to use the else if () statement.
By Nesting, I mean repeating your ternary block just after the colon ( : ) mark.
Now the colon mark can serve 2 functions which include;
- An else{} statement and
- else if() statement
Let me show you what I mean, using our previous example.
If we should rewrite the code above using the native if / else statements
Whichever method you choose, the output will still be the same, just like the images below.
Execute Multiple Actions in a Ternary Block
Now, for today’s tutorial, I will show you how to execute multiple codes/actions in a ternary block.
For us to be successful with this, we must group the actions together using a bracket, then we will separate the actions/codes using a comma.
Crazy right? Let us use the previous code to demonstrate this.
This is the output below
What’s the Logic?
Seriously no much logic was added to the code above.
We started off by declaring variables (x, y, and z ) and assigning zeros (0) to them.
Now we use a ternary block to check if they are empty or contain 0 values.
Any variable with a zero value can as well be said to be empty.
If the condition is true, we start reassigning the variables by grouping the block with a bracket then executing the actions one after the other by separating them with a comma.
Note that the last action to be executed does not need a comma after it.
That been said, I hope you now understand what you can do with Ternary Operators
If I find another interesting feature with regards to Ternary operators, I will keep you updated!
Thank You!