0
0
Javascriptprogramming~5 mins

Ternary operator in Javascript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the ternary operator in JavaScript?
The ternary operator is a shortcut for an if-else statement. It uses the syntax: condition ? valueIfTrue : valueIfFalse.
Click to reveal answer
beginner
How do you write a ternary operator to check if a number is even or odd?
Example: <code>let result = (num % 2 === 0) ? 'Even' : 'Odd';</code> This sets result to 'Even' if num is even, otherwise 'Odd'.
Click to reveal answer
intermediate
Can the ternary operator be nested in JavaScript?
Yes, you can nest ternary operators inside each other, but it can make code hard to read. Example: <code>let result = score > 90 ? 'A' : score > 80 ? 'B' : 'C';</code>
Click to reveal answer
beginner
What is the return value of a ternary operator?
The ternary operator returns the value of either the expression after the question mark if true, or the expression after the colon if false.
Click to reveal answer
beginner
Why use the ternary operator instead of if-else?
It makes simple conditional assignments shorter and easier to read, especially when assigning values based on a condition.
Click to reveal answer
What does the ternary operator syntax look like?
Acondition ? valueIfTrue : valueIfFalse
Bif (condition) { valueIfTrue } else { valueIfFalse }
Ccondition : valueIfTrue ? valueIfFalse
DvalueIfTrue ? condition : valueIfFalse
What will this code return? <br> let x = 5; let result = (x > 3) ? 'Yes' : 'No';
A'No'
B5
Cundefined
D'Yes'
Can ternary operators replace all if-else statements?
AYes, always
BNo, only simple conditions
COnly in loops
DOnly with numbers
What happens if the condition in a ternary operator is false?
AThe value after the colon is returned
BThe value after the question mark is returned
CAn error occurs
DThe condition is re-evaluated
Is this a valid ternary operator? <br> let a = 10; let b = a > 5 ? 'big' : 'small';
ANo
BOnly if a is a string
CYes
DOnly if a is less than 5
Explain how the ternary operator works and give a simple example.
Think of it as a short if-else that picks one of two values.
You got /4 concepts.
    Describe when you should use the ternary operator instead of if-else statements.
    Use it for quick decisions, not for complicated choices.
    You got /4 concepts.