Conditional Operator ( Ternary Operator ) Flashcards
1
Q
What is a Conditional Operator ? (Ternary)
A
It helps to write everything is one line.
It has 3 parts hence it is called as Ternary operator
- Condition Part
- IF part
- Else part
2
Q
Example for Conditional Operator ?
Reveal Answer
A
Example 1 :
age >= 18 ? console.log(‘I would like to drink wine’) :
console.log(‘I would like to drink Water’)
Output :- I would like to drink Water
Example 2 :
age = 21
const drink = age >= 23 ? ‘wine’ : ‘water’
console.log(drink)
3
Q
Coding Challenge ( Conditional Operator )
- If your country’s population is greater than 33 million, use the ternary operator to log a string like this to the console: ‘Portugal’s population is above average’.
Otherwise, simply log ‘Portugal’s population is below average’. Notice how only one word changes between these two sentences! - After checking the result, change the population temporarily to 13 and then to
- See the different results, and set the population back to original
A
console.log(${country}'s population is ${population > 33 ? 'above' :
'below'} average
,
);