Along with that same analogy of asking permission from parents, there was often the or else part of it. "You need to clean your room, or else you will be grounded for eternity."
So you really were being given two possible conditions: 1. Room cleaned. 2. Grounded for eternity.
We have the same logic in code with if else statements.
Sample Code
Here's a pretty standard example:
var age = 17;
if(age >= 18){
console.log("You can vote!");
}else{
console.log("You can't vote");
}
If the first condition is true and we are 18 or over, we can vote. The code executes and we're done. If that's not true, execute the code in the else block.
More Sample Code
Copy and paste the following code and play around with running it. Change variables and see what happens:
var elevatorUp = true;
var elevatorDown = true;
var elevatorBroken = true;
var elevatorStuckWhileWeAreOnIt = true;
var elevatorNumber = 13;
if (elevatorUp === true) { //Note: You don't have to have the ===
console.log("Going up");
} else {
console.log("Going down");
}
if (elevatorBroken) { //Note: You don't have to have the ===
console.log("Bummer. Let's take the stairs.");
} else {
console.log("Which floor?");
}
//Write another one for stuck:
if (elevatorStuckWhileWeAreOnIt){
console.log("Oh no! We're stuck!");
} else {
console.log("This elevator is fast.");
}
//But maybe we're standing there waiting?
if(elevatorBroken && elevatorDown){
console.log("I hope this thing doesn't start flying down!");
} else {
console.log("How long are you in town for?");
}
if(elevatorBroken || elevatorStuckWhileWeAreOnIt){
console.log("Hi Bob, this is Bob with maintenance. How can I help?");
}
//Using ints and other types
if(elevatorNumber === 13 && elevatorStuckWhileWeAreOnIt){
console.log("This is not our lucky day!");
}
Challenges
Pick one or both:
Challenge #1- Write your own conditional with some kind of story or theme like the one above. Make it about whatever you want: football, ponies, trains, etc.
Challenge #2- Fix the bank's bad code:
var bankAccount;
var debt = 4200;
var difference = bankAccount - debt;
console.log("I have $" + bankAccount " in my bank account, and I am $" + debt " in debt.");
if ((bankAccount - debt > 700) {
console.log("I have some extra money. I should pay off my debt. I'll have $" + difference + " leftover.");
} else
console.log("It probably isn't a good time to pay off my debt.');
}