Session 2.2 – Control Structures and Loops
Module 2: JavaScript & AJAX | Duration: 1 hr
Learning Objectives
By the end of this session, students will be able to:
- Implement conditional statements using if, else if, and else
- Use switch statements for multi-way branching
- Create loops using for, while, and do-while statements
- Apply loop control statements (break, continue)
- Understand and use nested loops effectively
Introduction to Control Flow
Control structures determine the order in which statements are executed in a program. JavaScript provides conditional statements for decision-making and loop statements for repetitive tasks.
What is Control Flow?
Control flow refers to the order in which individual statements, instructions, or function calls are executed. By default, JavaScript executes code sequentially from top to bottom, but control structures allow us to alter this flow based on conditions or repeat code multiple times.
Conditional Statements
1. if Statement
Executes a block of code if a specified condition is true.
// Basic if statement
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote");
}
// With multiple statements
let temperature = 30;
if (temperature > 25) {
console.log("It's hot outside");
console.log("Drink plenty of water");
}
2. if...else Statement
// if...else
let score = 75;
if (score >= 60) {
console.log("Pass");
} else {
console.log("Fail");
}
// Nested if...else
let num = 0;
if (num > 0) {
console.log("Positive number");
} else {
if (num < 0) {
console.log("Negative number");
} else {
console.log("Zero");
}
}
3. if...else if...else Statement
// Multiple conditions
let grade = 85;
if (grade >= 90) {
console.log("Grade: A");
} else if (grade >= 80) {
console.log("Grade: B");
} else if (grade >= 70) {
console.log("Grade: C");
} else if (grade >= 60) {
console.log("Grade: D");
} else {
console.log("Grade: F");
}
// Real-world example: Age classification
let userAge = 25;
if (userAge < 13) {
console.log("Child");
} else if (userAge < 20) {
console.log("Teenager");
} else if (userAge < 60) {
console.log("Adult");
} else {
console.log("Senior");
}
Best Practice
Always use curly braces {} even for single-line if statements to avoid bugs and improve readability. Use else if when you have mutually exclusive conditions, and remember that only the first matching condition will execute.
Switch Statement
The switch statement is used to perform different actions based on different conditions. It's more readable than multiple if...else if statements when checking a single variable against multiple values.
// Basic switch statement
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName); // "Wednesday"
Switch with Fall-Through
// Multiple cases sharing same code
let month = "March";
let season;
switch (month) {
case "December":
case "January":
case "February":
season = "Winter";
break;
case "March":
case "April":
case "May":
season = "Spring";
break;
case "June":
case "July":
case "August":
season = "Summer";
break;
case "September":
case "October":
case "November":
season = "Fall";
break;
default:
season = "Invalid month";
}
console.log(`${month} is in ${season}`); // "March is in Spring"
Switch vs If-Else
| Aspect | switch | if...else if |
|---|---|---|
| Use Case | Multiple equality checks on one variable | Complex conditions, range checking |
| Readability | More readable for many cases | Better for few conditions |
| Performance | Slightly faster for many cases | Sequential evaluation |
| Flexibility | Only equality checks | Any boolean expression |
JavaScript Loops
1. for Loop
Used when you know in advance how many times you want to execute a statement.
// Basic for loop
for (let i = 0; i < 5; i++) {
console.log(`Iteration: ${i}`);
}
// Output: 0, 1, 2, 3, 4
// Counting backwards
for (let i = 10; i >= 1; i--) {
console.log(i);
}
// Skip even numbers
for (let i = 1; i <= 10; i += 2) {
console.log(i); // 1, 3, 5, 7, 9
}
// Loop through array
let fruits = ["Apple", "Banana", "Orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(`${i + 1}. ${fruits[i]}`);
}
2. while Loop
Executes a block of code as long as a specified condition is true.
// Basic while loop
let count = 0;
while (count < 5) {
console.log(`Count: ${count}`);
count++;
}
// User input simulation
let password = "";
let attempts = 0;
const correctPassword = "secret123";
while (password !== correctPassword && attempts < 3) {
// In real scenario, get input from user
console.log(`Attempt ${attempts + 1}`);
attempts++;
}
// Countdown
let countdown = 5;
while (countdown > 0) {
console.log(countdown);
countdown--;
}
console.log("Blast off!");
3. do...while Loop
Similar to while loop, but executes the code block at least once before checking the condition.
// Basic do...while
let i = 0;
do {
console.log(`Value: ${i}`);
i++;
} while (i < 5);
// Executes at least once even if condition is false
let num = 10;
do {
console.log("This runs once");
} while (num < 5); // Condition is false, but runs once
// Menu system example
let choice;
do {
console.log("1. Start Game");
console.log("2. Settings");
console.log("3. Exit");
// choice = getUserInput(); // In real app
choice = 3; // Simulated
} while (choice !== 3);
4. for...of Loop (ES6)
Iterates over iterable objects (arrays, strings, etc.).
// Loop through array
let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
// Loop through string
let name = "JavaScript";
for (let char of name) {
console.log(char);
}
// With array of objects
let students = [
{name: "Alice", age: 20},
{name: "Bob", age: 22},
{name: "Charlie", age: 21}
];
for (let student of students) {
console.log(`${student.name} is ${student.age} years old`);
}
5. for...in Loop
Iterates over the properties of an object.
// Loop through object properties
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
city: "New York"
};
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
// Loop through array indices (not recommended)
let arr = ["a", "b", "c"];
for (let index in arr) {
console.log(`Index ${index}: ${arr[index]}`);
}
Loop Control Statements
1. break Statement
Terminates the loop and transfers control to the statement following the loop.
// Break when condition is met
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break; // Exit loop when i is 5
}
console.log(i); // Prints: 1, 2, 3, 4
}
// Search for item
let numbers = [2, 5, 8, 12, 15, 20];
let target = 12;
let found = false;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === target) {
console.log(`Found ${target} at index ${i}`);
found = true;
break; // Stop searching once found
}
}
// Break in while loop
let sum = 0;
let n = 1;
while (true) { // Infinite loop
sum += n;
if (sum > 100) {
break; // Exit when sum exceeds 100
}
n++;
}
console.log(`Sum: ${sum}, Last n: ${n}`);
2. continue Statement
Skips the rest of the current iteration and continues with the next iteration.
// Skip even numbers
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i); // Prints: 1, 3, 5, 7, 9
}
// Skip specific values
let scores = [85, -1, 92, 0, 78, -1, 88];
let validScores = [];
for (let score of scores) {
if (score < 0) {
continue; // Skip invalid scores
}
validScores.push(score);
}
console.log(validScores); // [85, 92, 0, 78, 88]
// Continue in while loop
let i = 0;
while (i < 10) {
i++;
if (i % 3 === 0) {
continue; // Skip multiples of 3
}
console.log(i); // Prints: 1, 2, 4, 5, 7, 8, 10
}
3. Nested Loops
// Multiplication table
for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= 5; j++) {
console.log(`${i} x ${j} = ${i * j}`);
}
console.log("---");
}
// Pattern printing
for (let i = 1; i <= 5; i++) {
let row = "";
for (let j = 1; j <= i; j++) {
row += "* ";
}
console.log(row);
}
// Output:
// *
// * *
// * * *
// * * * *
// * * * * *
// Break out of nested loops with labels
outerLoop: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outerLoop; // Breaks outer loop
}
console.log(`i=${i}, j=${j}`);
}
}
Practical Examples
Example 1: Number Guessing Game
// Simple number guessing game logic
function numberGuessingGame(secretNumber, maxAttempts) {
let attempts = 0;
let guess = 0;
while (attempts < maxAttempts && guess !== secretNumber) {
// In real app, get user input
guess = Math.floor(Math.random() * 10) + 1;
attempts++;
if (guess < secretNumber) {
console.log(`Attempt ${attempts}: ${guess} is too low`);
} else if (guess > secretNumber) {
console.log(`Attempt ${attempts}: ${guess} is too high`);
} else {
console.log(`Correct! Found ${secretNumber} in ${attempts} attempts`);
}
}
if (guess !== secretNumber) {
console.log(`Game Over! The number was ${secretNumber}`);
}
}
numberGuessingGame(7, 5);
Example 2: Prime Number Checker
// Check if a number is prime
function isPrime(num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 === 0 || num % 3 === 0) return false;
for (let i = 5; i * i <= num; i += 6) {
if (num % i === 0 || num % (i + 2) === 0) {
return false;
}
}
return true;
}
// Find all prime numbers up to n
function findPrimes(n) {
let primes = [];
for (let i = 2; i <= n; i++) {
if (isPrime(i)) {
primes.push(i);
}
}
return primes;
}
console.log(isPrime(17)); // true
console.log(findPrimes(30)); // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Example 3: Factorial Calculator
// Calculate factorial using different loop types
// Using for loop
function factorialFor(n) {
let result = 1;
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// Using while loop
function factorialWhile(n) {
let result = 1;
let i = 1;
while (i <= n) {
result *= i;
i++;
}
return result;
}
// Using do-while loop
function factorialDoWhile(n) {
if (n === 0) return 1;
let result = 1;
let i = 1;
do {
result *= i;
i++;
} while (i <= n);
return result;
}
console.log(factorialFor(5)); // 120
console.log(factorialWhile(5)); // 120
console.log(factorialDoWhile(5)); // 120
Example 4: FizzBuzz
// Classic FizzBuzz problem
function fizzBuzz(n) {
for (let i = 1; i <= n; i++) {
if (i % 15 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
}
fizzBuzz(15);
// Output: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz
Session Summary
Key Points
- Conditional statements (if, else if, else) control program flow based on conditions
- Switch statements provide a cleaner way to handle multiple equality checks
- for loops are ideal when you know the number of iterations in advance
- while loops continue as long as a condition is true
- do...while loops execute at least once before checking the condition
- for...of loops iterate over array values, for...in loops iterate over object keys
- break exits a loop completely, continue skips to the next iteration
- Nested loops allow you to work with multi-dimensional data structures
Next Session Preview
In the next session, we will explore Strings, Arrays, and Objects in JavaScript, including their properties, methods, and manipulation techniques.