ICS3U - Mr. Brash 🐿️ (Click here for Part 1)
The if-else
statement allows us to make decisions with code:
if (lives == 0) {
console.log("Game over!")
}
But what if we needed to make several decisions based on fairly complex conditions?
For example - the user selects a colour based on a number:
let selection = prompt("Enter 1 for red, 2 for blue, 3 for green, 4 for purple")
if (selection == 1) {
// Do something
}
if (selection == 2) {
// Do something else
}
if (selection == 3) {
// Do something else
}
if (selection == 4) {
// Do something else
}
In the above example, the code is going to check the variable selection
FOUR times, even if the user entered "1" or a number not in the list, like "8". That's a lot of wasted checking.
The else if
block will only be checked if the condition above it was false
.
Let's retry our colour selection example:
let selection = prompt("Enter 1 for red, 2 for blue, 3 for green, 4 for purple")
if (selection == 1) {
// Do something
} else if (selection == 2) {
// Do something else
} else if (selection == 3) {
// Do something else
} else if (selection == 4) {
// Do something else
} else {
// for all other cases, do this
}
Notice in the code above, if the user enters "2", the code will check if it's equal to 1 (it's not), then check if it's equalt to 2 (it is) and it will NOT check any of the other conditions - it will run the block of code for == 2
.
Also notice the final else
statement. What if the user enters 99? The else
block catches all other scenarios (anything that wasn't caught within the conditions).
Note:
- You can have as many
else if
statements as you need but only oneif
. - You can only have one
else
statement. It is optional and it must be last.
- To get the length of a String, we can use
.length
For Example:
let name = "Mr. Squirrel" console.log("Your name is", name.length, "characters long.")
- The internet is full of tutorials, more tutorials, and examples about the if-else statement since it is one of the very first constructs people learn in programming.
🐿️