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
let age = 18;
if (age >= 18) {
console.log("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
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");
}
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
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");
}

💡 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.
| Loop Type | Description |
|---|---|
for | Runs a block a specific number of times using an initializer, condition, and increment. |
while | Runs as long as a condition remains true. |
do...while | Runs at least once, then repeats while condition is true. |
6. Example: for Loop
📌 Deep Dive: Simple for Loop
for (let i = 1; i <= 3; i++) {
console.log("Count:", i);
}
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, andelsecontrol conditional branching.switchhandles multiple possible values cleanly.- Loops (
for,while,do...while) repeat code blocks efficiently.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which statement is used to execute code only when a condition is true?
Question 2 of 2
What does the break statement do inside a switch?
Loading results...