- What is a conditional statement? Give three examples.
A conditional statement: is one where a decision must be made.
- e.g.: Is it too loud outside? If yes, close the window. If no, keep the window open.
- e.g. 2: Are you allergic to nuts? If yes, you can't eat the cookie. If no, you can eat the cookie.
- e.g. 3: Is it your bedtime? If yes, go to sleep. If no, you can play.
- Why might you want to use an if-statement?
You might want to use an if-statement when you want to give a script two or more options of what could happen next. What happens next is determined by what condition is met.
- What is the JavaScript syntax for an if statement?
if (condition) {
// code to execute when above condition is met
}
- How do you add multiple conditions to an if statement?
You can add multiple conditions to an if statement by using ||
or &&
between the two conditions.
if ((condition) || (condition))
or if ((condition) && (condition))
- What is the JavaScript syntax for an if/else if/else statement?
if (condition) {
// code to execute when one condition is met
} else if (condition 2) {
// code to execute when another condition is met
} else {
// code to execute for all other conditions
}
- Other than an if-statement, can you think of any other ways we might want to use a conditional statement?
Another way to use a conditional statement is a switch statement.