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.
const age = 18; const canVote = age >= 18 ? 'Yes' : 'No'; console.log(canVote);
| Step | Condition (age >= 18) | Result | Value assigned to canVote | Output |
|---|---|---|---|---|
| 1 | 18 >= 18 | true | 'Yes' | No output yet |
| 2 | N/A | N/A | N/A | Print 'Yes' |
| Variable | Start | After Step 1 | Final |
|---|---|---|---|
| age | undefined | 18 | 18 |
| canVote | undefined | 'Yes' | 'Yes' |
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.
condition ? expr1 : expr2 do in JavaScript?condition ? expr1 : expr2. It checks the condition.condition is true, it returns expr1. Otherwise, it returns expr2.condition ? expr1 : expr2 with a question mark and colon separating parts.const age = 20; const canVote = age >= 18 ? 'Yes' : 'No'; console.log(canVote);
age >= 18age is 20, which is greater than or equal to 18, the condition is true.canVotecanVote is assigned the string 'Yes'.let score = 85; let grade = score > 90 ? 'A' : score > 80 ? 'B' : 'C'; console.log(grade);
score = 85score > 90 is false, so it checks score > 80, which is true, so grade is 'B'.status based on a number score: if score is 0 or less, status should be 'Fail'; if between 1 and 50, 'Pass'; otherwise 'Excellent'. Which ternary expression correctly does this?statusscore <= 0 means 'Fail', between 1 and 50 means 'Pass', and above 50 means 'Excellent'.score <= 0 for 'Fail', then score <= 50 for 'Pass', else 'Excellent'. Others have wrong ranges or conditions.Pass the test and this pattern moves unknown