Everyone has heard or used ternary operators in different places and different languages. In Javascript ternary operator has some more powers that most developers aren't aware of.
How does a Ternary look like
// Ternary Operator
Parameter / Argument ? Statement_to_be_Executed : Else_Statement_to_be_executed
P ? S1 : S2
It is the most simplest and convenient form of conditional statements
1st Power of Ternary operator
A ternary operator can be used to store expression into a variable which will produce a boolean value.
It can be used if we have multiple condition to work with rather than having multiple nested if statement we can use Ternary Operator
Example : Here Sarah want to get a Drivers Licence and Below are two logics given one with a nested if statements and another with a ternary Operator. To get the drivers licence sarah age should be equal or morethan the require again and should have passed licence test with minimum points required.
// Using nested If statement
let sarahAge = 23;
let sarahScorePoints = 30;
let requiredPoints = 30;
let minimumAgeRequired= 20;
if (sarahAge > minimumAgeRequired) {
if (sarahScorePoints >= requiredPoints) {
console.log("Sarah Can get a Drivers Licence");
} else {
console.log("Sarah can't get a Drivers Licence");
}
}
// Using the ternary operator
let sarahtestpoints = 30;
let sarahage = 30;
let sarahtestscorepoints =
sarahtestpoints >= 30
? `and scored ${sarahtestpoints} in licence test`
: `and scored ${sarahtestpoints} in licence test`;
if (sarahage > 20) {
console.log(`Sarah age is above the age required ${sarahtestscorepoints}`);
} else {
console.log(`Sarah age is below the age required ${sarahtestscorepoints}`);
}
If statement Output
> Sarah can get a Drivers licence
Ternary Operator Output
> Sarah age is above the age requirement and scored 30 points in licence test
2nd power of Ternary operator
Ternary operator can be used to produced an expression inside a string before logging to console.
// Here we are using template literal
let sarahage = 20;
console.log(`Sarah ${sarahage >= 20 ? 'can get licence' : "can't get licence" }`);
> Sarah can get licence
Ternary operator can't be used for complex conditions