JavaScript: Conditional Statements Flashcards
What is the syntax for an “if statement?”
const hungerLevel = 50;
const isLunchTime = true;
const lunchBill = 11;
…
Evaluates to true so “Hungry” is logged:
if (hungerLevel >= 50) {
console.log(“Hungry!”);
}
Evaluates to false so nothing is logged:
if (hungerLevel < 50) {
console.log(“I’m full!”);
}
Steps:
To create an if statement in JavaScript, follow these steps:
1. Begin the if statement with the if keyword.
2. Inside the parentheses (), add a condition that evaluates to true or false.
3. If the condition is true, execute the code inside the curly braces {}.
4. Optionally, add an else statement after the if statement to specify code that will execute if the condition is false.
What is the syntax for an “else statement?”
const hungerLevel = 50;
const isLunchTime = true;
const lunchBill = 11;
…
Evaluates to true so “Lunchtime” is logged:
if (isLunchTime === true) {
console.log(“Lunchtime”);
} else {
console.log(“Not Lunchtime”);
}
Shorthand for the following:
if (isLunchTime === true) {
console.log(“Lunchtime”);
} else {
console.log(“Not Lunchtime”);
}
if (isLunchTime) {
console.log(“Lunchtime!!”);
} else {
console.log(“Not Lunchtime!!”);
}
Example of how “Else if” allows you to test more than one condition
The first condition is false, so the second condition is evaluated. Logs “Cost Rating: $$”
if (lunchBill < 10) {
console.log(“Cost Rating: $”);
} else if (lunchBill >= 10 && lunchBill < 15) {
console.log(“Cost Rating: $$”);
} else {
console.log(“Cost Rating: $$$”);
}