A lot of people get confused when it comes to ternary operations but it is really not that hard. In this article, I will help you understand ternary operators.
First, what is a ternary operator
A ternary operator is a conditional statement that evaluates a condition and executes a block of code based on the condition. A ternary operator can be used to simplify an if...else statement. The ternary operator is the only Javascript operation that takes three oprands rather than the typical one or two that most operators use.
The syntax is below ⬇️:
condition ? expression1 : expression2
That is:
If the condition is true, expression1 is executed.
If the condition is false, expression2 is executed.
Using Ternary Operators instead of IF...Else statements
You will no longer write a conditional statement and keep indenting like this:
// check the age to determine the eligibility to drive
let age = 16;
let result = 18;
if (age === 18) {
result= 'You can now drive, '
} else {
result= 'You cannot drive, too young'
}
console.log(`result is '${result}'`);
but you can write it easily like this:
let age = 16
let result = (age === 18) ? 'You can now drive' : 'You cannot drive, you are too young'
console.log(`result is '${result}'`)
This line of code just reads out:
Result if the age is greater than 18 then console.log you can drive else console.log you cannot drive, you're too young
Note It's not advised to replace multiple if else... statements with multiple ternary operators because it makes the code harder to read in the future. It's best to stick with either if/else or switch statements for such cases.
Conclusion
A ternary operator is just an easier way of writing If else.. statements. It is an easier and cleaner way of assigning your variables.
For more Information on ternary operations check out the resources below: freecodecamp.org/news/ternary-operator-java.. codecademy.com/courses/introduction-to-java.. computerhope.com/jargon/t/ternaryoperator.htm