Ternary Operator, online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
Ternary Operator in one minute
What students need to know
This is exactly the pattern the ternary operator follows. The colon divides the value used for true from the value for false.
The ternary operator always pairs ? with a matching :. It condenses a simple if/else into a single expression.
Mistakes students make
- Ternary condition uses ?, not =, before the values.
- Ternary needs ?, not -, after the condition.
- Ternary needs :, not ;, between the two values.
- Missing the colon : between the two ternary values.
PREVIOUS · MODULE 16else Statements
YOU ARE HERE · MODULE 17Ternary Operator
NEXT · MODULE 18switch Statement
What students will learn in this module
Every question in Module 17
Quick questions
- Does the ternary operator use ? and : together?AYesBNo
- Is the ternary operator a shorthand for if/else?ANoBYes
- Does = replace ? in a correct ternary expression?AYesBNo
- Can a ternary expression's result be stored in a variable?AYesBNo
- Does the condition need a semicolon before the ?ANoBYes
Key terms
Students type the meaning of:
?:
Match the pairs
age >= 18 ? "adult" : "minor"Match it to what it doesscore > 50 ? "win" : "lose"Match it to what it doesA shorthand way of writing an if/else statementMatch it to what it doesSeparates the true and false results in a ternaryMatch it to what it doeslet x = a = "yes" : "no";Match it to what it doeslet y = a ? "yes" - "no";Match it to what it doesFill in the blanks
let status = age >= 18 _ "adult" : "minor";
Hint: Type the symbol that starts the ternary operator.
let result = score > 50 ? "win" _ "lose";
Hint: Type the symbol that separates the two ternary values.
let label = isReady _ "Go" : "Wait";
Hint: Type the symbol that starts the ternary operator.
let output = temp > 30 ? "hot" _ "cool";
Hint: Type the symbol that separates the two ternary values.
let grade = pass _ "Pass" : "Fail";
Hint: Type the symbol that starts the ternary operator.
Spot the error
Question 1
Alet x = ok = "a" : "b";Bconsole.log(x);Clet y = 5;
Question 2
Alet a = 5;Blet b = x > 3 - "hi" : "lo";Cconsole.log(b);
Question 3
Alet n = 10;Blet z = 1;Clet lab = n==10 ? "a" ; "b";Dconsole.log(lab);
Question 4
Alet age = 20;Blet t;Cconsole.log(t);Dt = age>=18 ? "a" "b";
Question 5
Alet s = 75;Blet r;Cconsole.log(r);Dlet ok2 = true;Er = s>=50 && "p" : "f";
