What is it?
As it's name suggests, is an operator that takes 3 parameters (only one in JavaScript that takes 3), the first one is the condition, the second one is what will be returned or executed if the condition is true, the last one is what will be returned or executed if the condition is false.
This definition is very vague so let's see some examples
Examples
Replacing a simple if..else statement
This can be replaced for this
Returning a value
Defining a variable
Concatenating ternary operators
You can concatenate as many as you want, but don't over use it or it will end up being a nice plate of spaghetti code
When to use it
- When the code to execute is short
If the expression is not very simple, then it's not a good idea to use it
- When there's no more than 1 condition
As ****I said, you can concatenate as many as you want, but it will end up being hard to read, so keep it with only one condition (sometimes 2 will be ok)
Exercises
You can make this exercises online here
Replace this if...else statement
Replace this returning statement
Replace this variable definition
Solutions
Exercise 1
Exercise 2
Exercise 3
I hope this was useful to you and consider following me on Twitter, I'll be posting daily JavaScript content there
Top comments (0)