Simple conditionals
Explore
Play a game where students react to different situations based on instructions. For example:
- Start the game with just an if statement
if (shoeColor === `white`) { raiseRightHand() } - Then add in an else
Add an else-if
if (shoeColor === `white`) { raiseRightHand() } else if (shoeColor === `blue`) { raiseLeftHand() } else { clap() }- Students interpret the rules. If they do the wrong actions they sit down.
Questions
- What was special about the equals signs used in the if statements?
- Why are conditionals (if and else) important?
- What do you think you could use conditionals for in your code?
Explain
As a group, build an application that only responds if the user inputs the word hello
Start by asking students, "How many inputs do we need to create this application? What should it be called?"
This application need one input. A simple name could be input but the name of the parameter doesn't matter.function main (input) { }How can the program check if the user inputed hello?
Add an if statement. The if should check if input is equal to the string `hello`.function main (input) { if (input === `hello`) { } }- Choose how the application should responds
function main (input) { if (input === `hello`) { return `Thanks for saying hello` } }
Engage
Create conditional codewars exercises
- Comparing values handout - https://www.weo.io/activity/577409e042d5437c00d65614/public/preview/
Personalized greeting - https://www.codewars.com/kata/5772da22b89313a4d50012f7/train/javascript
Solution:
function greet (name, owner) { if (name === owner) { return `Hello boss` } else { return `Hello guest` } }Calculator - https://www.codewars.com/kata/basic-mathematical-operations
Solution:
function basicOp (op, num1, num2) { if (op === `+`) { return num1 + num2 } else if (op === `-`) { return num1 - num2 } else if (op === `*`) { return num1 * num2 } else if (op === `/`) { return num1 / num2 } else { return `I can't do that operation` } }