Control Flow

Control flow in JavaScript determines the order in which statements are executed. It allows your program to make decisions and repeat actions based on conditions, enabling dynamic behavior.

1. if Statement

Executes a block of code only if a specified condition is true.

📌 Deep Dive: Basic if Statement

JAVASCRIPT
let age = 18;
if (age >= 18) {
  console.log("You are an adult.");
}
Output
You are an adult.

2. if...else Statement

Provides an alternative block to execute when the condition is false.

3. else if Ladder

Checks multiple conditions in sequence.

📌 Deep Dive: if...else if...else Structure

JAVASCRIPT
let score = 75;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B");
} else if (score >= 70) {
  console.log("Grade: C");
} else {
  console.log("Grade: F");
}
Output
Grade: C

4. switch Statement

Evaluates an expression and executes code blocks based on matching cases. Useful when comparing one value against many possible cases.

📌 Deep Dive: Using switch

JAVASCRIPT
let color = "red";

switch (color) {
  case "blue":
    console.log("Color is blue");
    break;
  case "red":
    console.log("Color is red");
    break;
  default:
    console.log("Color not recognized");
}
Output
Color is red
Illustration of control_flow
Illustration of control_flow

💡 Remember:

The break statement stops execution inside a switch block after a match is found. Omitting it causes "fall-through" behavior.

5. Loops for Repetition

Loops execute a block of code multiple times based on conditions.

Common Loop Types
Loop TypeDescription
forRuns a block a specific number of times using an initializer, condition, and increment.
whileRuns as long as a condition remains true.
do...whileRuns at least once, then repeats while condition is true.

6. Example: for Loop

📌 Deep Dive: Simple for Loop

JAVASCRIPT
for (let i = 1; i <= 3; i++) {
  console.log("Count:", i);
}
Output
Count: 1
Count: 2
Count: 3

⚠️ Infinite Loops Warning

Ensure loop conditions eventually become false to avoid infinite loops that freeze or crash programs.

Summary

  • if, else if, and else control conditional branching.
  • switch handles multiple possible values cleanly.
  • Loops (for, while, do...while) repeat code blocks efficiently.