JavaScript Control Flow — Complete Guide
Phase 2 — Control Flow
Module 6 — Conditional Statements and Loops
Control flow determines the order in which JavaScript executes statements. Without control flow, every line of code would execute sequentially from top to bottom.
Control flow allows programs to:
- Make decisions
- Repeat tasks
- Skip unnecessary code
- Exit loops
- Navigate nested loops
Every professional JavaScript application uses control flow extensively—from validating forms to processing API responses and rendering user interfaces.
What is Control Flow?
Control flow is the process of deciding which code should execute, when it should execute, and how many times it should execute.
1Program Starts 2 │ 3 ▼ 4 Condition? 5 ┌───────────┐ 6 │ True │ 7 ▼ ▼ 8Execute A Execute B 9 │ 10 ▼ 11 Continue Program
Categories of Control Flow
1Control Flow 2 3│ 4 5├── Conditional Statements 6│ ├── if 7│ ├── else 8│ └── switch 9│ 10├── Loops 11│ ├── while 12│ ├── do...while 13│ ├── for 14│ ├── for...of 15│ └── for...in 16│ 17└── Loop Control 18 ├── break 19 ├── continue 20 └── labels
if Statement
The if statement executes code only when a condition evaluates to true.
Syntax
1if (condition) { 2 // code 3}
Example
1let age = 20; 2 3if (age >= 18) { 4 console.log("You can vote."); 5}
Output
1You can vote.
if...else Statement
Execute one block if the condition is true; otherwise execute another block.
1let age = 16; 2 3if (age >= 18) { 4 console.log("Adult"); 5} else { 6 console.log("Minor"); 7}
Output
1Minor
else if Ladder
Useful when checking multiple conditions.
1let marks = 82; 2 3if (marks >= 90) { 4 console.log("Grade A"); 5} 6else if (marks >= 75) { 7 console.log("Grade B"); 8} 9else if (marks >= 60) { 10 console.log("Grade C"); 11} 12else { 13 console.log("Fail"); 14}
Output
1Grade B
Nested if
An if statement can be placed inside another if.
1let age = 22; 2let hasLicense = true; 3 4if (age >= 18) { 5 if (hasLicense) { 6 console.log("You can drive."); 7 } 8}
Output
1You can drive.
switch Statement
The switch statement is useful when comparing one value against multiple possible cases.
Syntax
1switch (expression) { 2 case value: 3 // code 4 break; 5 6 default: 7 // code 8}
Example
1let day = 3; 2 3switch (day) { 4 case 1: 5 console.log("Monday"); 6 break; 7 8 case 2: 9 console.log("Tuesday"); 10 break; 11 12 case 3: 13 console.log("Wednesday"); 14 break; 15 16 default: 17 console.log("Invalid Day"); 18}
Output
1Wednesday
Switch Fall-Through
Without break, execution continues into the next case.
1let value = 1; 2 3switch (value) { 4 case 1: 5 console.log("One"); 6 7 case 2: 8 console.log("Two"); 9}
Output
1One 2Two
Always use break unless fall-through is intentional.
while Loop
Executes repeatedly while a condition is true.
Syntax
1while (condition) { 2 // code 3}
Example
1let i = 1; 2 3while (i <= 5) { 4 console.log(i); 5 i++; 6}
Output
11 22 33 44 55
Infinite while Loop
1while (true) { 2 console.log("Running..."); 3}
Always ensure the loop has a condition that eventually becomes false.
do...while Loop
Runs the loop body at least once, even if the condition is false.
1let count = 1; 2 3do { 4 console.log(count); 5 count++; 6} while (count <= 5);
Output
11 22 33 44 55
Example when the condition is initially false:
1let number = 10; 2 3do { 4 console.log(number); 5} while (number < 5);
Output
110
for Loop
The most commonly used loop in JavaScript.
Syntax
1for (initialization; condition; update) { 2 3}
Example
1for (let i = 1; i <= 5; i++) { 2 console.log(i); 3}
Output
11 22 33 44 55
Nested for Loop
1for (let row = 1; row <= 3; row++) { 2 3 for (let col = 1; col <= 3; col++) { 4 console.log(row, col); 5 } 6 7}
Output
11 1 21 2 31 3 42 1 5...
for...of Loop
Used for iterating over iterable objects.
Works with:
- Arrays
- Strings
- Maps
- Sets
Example
1const colors = ["Red", "Blue", "Green"]; 2 3for (const color of colors) { 4 console.log(color); 5}
Output
1Red 2Blue 3Green
String Example
1const language = "JavaScript"; 2 3for (const letter of language) { 4 console.log(letter); 5}
for...in Loop
Used for iterating over object properties.
1const user = { 2 name: "Ankit", 3 age: 23, 4 city: "Delhi" 5}; 6 7for (const key in user) { 8 console.log(key, user[key]); 9}
Output
1name Ankit 2age 23 3city Delhi
for...of vs for...in
| Feature | for...of | for...in |
|---|---|---|
| Arrays | ✅ | ⚠️ (indexes) |
| Objects | ❌ | ✅ |
| Strings | ✅ | ❌ |
| Values | ✅ | ❌ |
| Keys | ❌ | ✅ |
break Statement
The break statement immediately terminates a loop or switch statement.
Example
1for (let i = 1; i <= 10; i++) { 2 3 if (i === 5) { 4 break; 5 } 6 7 console.log(i); 8 9}
Output
11 22 33 44
break with switch
1let fruit = "Apple"; 2 3switch (fruit) { 4 5 case "Apple": 6 console.log("Selected Apple"); 7 break; 8 9 default: 10 console.log("Unknown"); 11 12}
continue Statement
The continue statement skips the current iteration and moves to the next one.
1for (let i = 1; i <= 5; i++) { 2 3 if (i === 3) { 4 continue; 5 } 6 7 console.log(i); 8 9}
Output
11 22 34 45
Labels
Labels allow you to control nested loops.
Syntax
1labelName: 2 3for (...) { 4 5}
Example
1outerLoop: 2 3for (let i = 1; i <= 3; i++) { 4 5 for (let j = 1; j <= 3; j++) { 6 7 if (i === 2 && j === 2) { 8 break outerLoop; 9 } 10 11 console.log(i, j); 12 13 } 14 15}
Output
11 1 21 2 31 3 42 1
continue with Labels
1outer: 2 3for (let i = 1; i <= 3; i++) { 4 5 for (let j = 1; j <= 3; j++) { 6 7 if (j === 2) { 8 continue outer; 9 } 10 11 console.log(i, j); 12 13 } 14 15}
Output
11 1 22 1 33 1
Choosing the Right Loop
| Situation | Recommended Loop |
|---|---|
| Fixed number of iterations | for |
| Unknown number of iterations | while |
| Execute at least once | do...while |
| Iterate array values | for...of |
| Iterate object properties | for...in |
Common Mistakes
Forgetting break in switch
1switch (role) { 2 3 case "admin": 4 console.log("Admin"); 5 6 case "user": 7 console.log("User"); 8 9}
Both cases execute due to fall-through.
Infinite Loop
1let i = 1; 2 3while (i <= 5) { 4 console.log(i); 5}
i is never incremented.
Using for...in for Arrays
1const numbers = [10, 20, 30]; 2 3for (const index in numbers) { 4 console.log(index); 5}
Output
10 21 32
To access values directly, use for...of.
Best Practices
- Use
if...elsefor complex conditional logic. - Use
switchwhen comparing one variable against many constant values. - Prefer
forloops for counting iterations. - Use
for...ofto iterate arrays, strings, maps, and sets. - Use
for...inonly for object properties. - Always use
breakinswitchstatements unless fall-through is intentional. - Avoid labels unless dealing with complex nested loop logic.
- Ensure every loop has a terminating condition.
Mini Project: Student Grade Analyzer
index.html
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <title>Student Grade Analyzer</title> 6</head> 7<body> 8 9<h2>Student Results</h2> 10 11<div id="output"></div> 12 13<script src="script.js"></script> 14 15</body> 16</html>
script.js
1const students = [ 2 { name: "Ankit", marks: 92 }, 3 { name: "Rahul", marks: 68 }, 4 { name: "Priya", marks: 81 }, 5 { name: "Neha", marks: 45 } 6]; 7 8const output = document.getElementById("output"); 9 10for (const student of students) { 11 12 let grade; 13 14 if (student.marks >= 90) { 15 grade = "A"; 16 } else if (student.marks >= 75) { 17 grade = "B"; 18 } else if (student.marks >= 60) { 19 grade = "C"; 20 } else { 21 grade = "D"; 22 } 23 24 output.innerHTML += ` 25 <p> 26 <strong>${student.name}</strong> : 27 ${student.marks} Marks 28 (Grade ${grade}) 29 </p> 30 `; 31}
Summary
In this module, you learned:
- How
if,else, andelse ifcontrol decision-making. - When to use the
switchstatement and howbreakprevents fall-through. - How
while,do...while, andforloops execute repeated tasks. - The differences between
for...ofandfor...in. - How
breakexits a loop orswitch, whilecontinueskips the current iteration. - How labels can control nested loops, and why they should be used sparingly.
- Best practices for selecting the right control flow structure for different programming scenarios.
In the next module, you'll learn JavaScript Functions, including function declarations, expressions, arrow functions, parameters, default parameters, rest parameters, callbacks, closures, recursion, higher-order functions, and immediately invoked function expressions (IIFEs), which form the foundation of reusable and modular JavaScript code.