0
0
Javascriptprogramming~10 mins

Ternary operator in Javascript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Ternary operator
Evaluate condition
Yes/No
True
Return true_value
End
The ternary operator checks a condition and returns one value if true, another if false.
Execution Sample
Javascript
const age = 18;
const canVote = age >= 18 ? 'Yes' : 'No';
console.log(canVote);
This code checks if age is 18 or more and sets canVote to 'Yes' or 'No' accordingly.
Execution Table
StepCondition (age >= 18)ResultValue assigned to canVoteOutput
118 >= 18true'Yes'No output yet
2N/AN/AN/APrint 'Yes'
💡 Condition true, so 'Yes' assigned and printed.
Variable Tracker
VariableStartAfter Step 1Final
ageundefined1818
canVoteundefined'Yes''Yes'
Key Moments - 2 Insights
Why does the ternary operator return 'Yes' when age is 18?
Because the condition age >= 18 is true at step 1 in the execution table, so the true value 'Yes' is assigned.
What happens if the condition is false?
If the condition is false, the ternary operator assigns the false value (here 'No'), as shown in the concept flow diagram.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of canVote after step 1?
Aundefined
B'No'
C'Yes'
Dnull
💡 Hint
Check the 'Value assigned to canVote' column in row for step 1.
At which step is the output printed to the console?
AStep 2
BBefore step 1
CStep 1
DNo output is printed
💡 Hint
Look at the 'Output' column in the execution table.
If age was 16, what would be the value assigned to canVote at step 1?
A'Yes'
B'No'
Cundefined
DError
💡 Hint
Refer to the concept flow and how false condition returns the false value.
Concept Snapshot
Syntax: condition ? true_value : false_value
Evaluates condition first.
Returns true_value if condition is true.
Returns false_value if condition is false.
Used for quick if-else assignments.
Full Transcript
The ternary operator in JavaScript evaluates a condition and returns one of two values depending on whether the condition is true or false. In the example, age is checked if it is 18 or more. Since age is 18, the condition is true, so 'Yes' is assigned to canVote. Then 'Yes' is printed. If the condition were false, 'No' would be assigned instead. This operator is a shortcut for simple if-else statements.