Programs rarely run in a straight line. You often need to execute certain code only if a condition is met, or repeat an action multiple times. This is called control flow.

Conditional Statements

1. The if...else Statement The if statement executes a block of code if a specified condition is true. You can use an optional else block to execute code if the condition is false, and else if to check multiple conditions.

Code Snippet: Grading System

JavaScript


const score = 85;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B"); // This block will run
} else if (score >= 70) {
  console.log("Grade: C");
} else {
  console.log("Grade: F");
}

2. The switch Statement A switch statement can be a cleaner alternative to a long if...else if chain when you are comparing a single value against multiple possibilities.

Code Snippet: Handling User Roles

JavaScript


const userRole = "admin";

switch (userRole) {
  case "admin":
    console.log("Full access granted.");
    break; // The 'break' keyword is crucial! It exits the switch.
  case "editor":
    console.log("Can edit content.");
    break;
  case "viewer":
    console.log("View-only access.");
    break;
  default: // Runs if no other case matches
    console.log("Unknown role.");
}

Loops

Loops are used to execute a block of code repeatedly.

1. The for Loop The for loop is great when you know exactly how many times you want to loop. It consists of three parts: initialization, condition, and increment.

Code Snippet: Counting to 5

JavaScript


// for (initialization; condition; increment)
for (let i = 1; i <= 5; i++) {
  console.log("The current number is " + i);
}
// Output:
// The current number is 1
// The current number is 2
// ...
// The current number is 5

2. The while Loop A while loop continues to execute as long as its condition remains true. It's useful when you don't know the exact number of iterations beforehand.

Code Snippet: A Simple Game Loop

JavaScript


let playerHealth = 100;
let monsterAttack = 15;
let turn = 1;

while (playerHealth > 0) {
  console.log(`Turn ${turn}: Player health is ${playerHealth}.`);
  playerHealth -= monsterAttack; // Player takes damage
  turn++;
}

console.log("Game over! Player has been defeated.");