Conditionals

What are conditionals?

Conditionals are statements that run different code based on whether a condition is true or false. They let your program make decisions and respond to different situations.

Benefits of conditionals?

  • Make decisions based on game state
  • Control different behaviors for different situations
  • Handle player input and respond appropriately
  • Check errors and handle problems
  • Create dynamic, responsive programs
const playerHealth = 50;

if (playerHealth <= 0) {
    console.log("Game Over!");
}

// if...else
if (playerHealth > 75) {
    console.log("Player is healthy!");
} else {
    console.log("Player needs healing!");
}

// if...else if...else
const levelScore = 2500;

if (levelScore >= 5000) {
    console.log("Gold medal!");
} else if (levelScore >= 3000) {
    console.log("Silver medal!");
} else if (levelScore >= 1000) {
    console.log("Bronze medal!");
} else {
    console.log("Try again!");
}

// switch
const playerAction = "jump";
switch (playerAction) {
    case "jump":
        console.log("Player jumps!");
        break;
    case "run":
        console.log("Player runs!");
        break;
    default:
        console.log("Unknown action");
}

What does this code do?

  • Uses nested if statements to check conditions in sequence
  • Only checks next condition if previous one was true
  • Shows practical game logic: player must be alive AND have weapon AND target in range to attack
  • Each level of nesting adds another requirement
  • Demonstrates hierarchical decision-making
  • Real-world example: how games control what players can do

Try It Yourself

%%js // CODE_RUNNER: conditionals const health = 75; if (health > 80) { console.log(“Good health”); } else if (health > 30) { console.log(“Fair health”); } else { console.log(“Critical”); }