1-7 If...Else Statements

If...Else Statements are conditional statements that are used to perform different actions based on different conditions. Conditional statements allow a computer program to make decisions based on the given conditions.

Basic Syntax

if (condition) {
    code to be executed if the condition is true;
} else { 
    code to be executed if the condition is false;
}

Example:

if (score = 10) {
    scoreMessage = 'Great job!';
} else {
    scoreMessage = 'Better luck next time!';
}

Based on this code, if the score value is 10 (meaning the condition is True), "Great job!" will display. If the score is anything besides 10 (meaning the condition is False), "Better luck next time!" will display.

Else If Statements

When you need to have multiple conditions to check against, you can use an Else If statement. The syntax is a little different than a basic If...Else statement.

if (condition1) {
    code to be executed if condition1 is true;
} else if (condition2) {
    code to be executed if the condition1 is false and condition2 is true;
} else {
    code to be executed if the condition1 is false and condition2 is false;
}

Example:

if (energyLevel > 99) {
    energyTank = game.add.sprite(game.world.centerX, game.world.centerY, 'fullEnergyTank');
} else if (energyLevel > 20) {
    energyTank = game.add.sprite(game.world.centerX, game.world.centerY, 'lowEnergyTank');
    screenMessage = 'Your energy tanks are getting low!';
} else {
    energyTank = game.add.sprite(game.world.centerX, game.world.centerY, 'emptyEnergyTank');
    screenMessage = 'Game Over';
}

Based on the If Else statement above, if the value of energyLevel is greater than 99, the fullEnergyTank image will display and nothing else will happen. If energyLevel isn't greater than 99 (less than or equal to 99), it will check against the 2nd condition. If the value of energyLevel is greater than 20, the lowEnergyTank image will display and a message will display on the screen saying the energy tanks are low. If both of the conditions above were false, the emptyEnergyTank image will display, and the screen will display a Game Over message.

More Information

Last updated