December 2024 class - Switch, Loops, and Functions
December 2024 class - Switch, Loops, and Functions
https://thePracticalIT.com
(240) 877-8161 | [email protected]
911 Silver Spring Ave STE 101, Silver Spring MD 20910
Lab Session: Switch Case, Loops (for, while, do...while, continue, break),
and Functions
Objective: This lab manual is designed to help you understand and practice fundamental
JavaScript concepts: Switch Case, Loops (for, while, do...while, continue, break), and
Functions. Each section includes an explanation, syntax, examples, and hands-on exercises to
reinforce your learning.
Explanation
The switch statement evaluates an expression and matches its value to a case label. If a match
is found, the corresponding block of code executes. The break keyword prevents "fall-through"
to subsequent cases, and default handles unmatched cases.
Syntax
switch (expression) {
case value1:
// Code to execute if expression === value1
break;
case value2:
// Code to execute if expression === value2
break;
default:
// Code to execute if no case matches
}
Example:
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Invalid day";
}
Exercises
1. Write a switch statement to determine the month name based on a number (1-12). Test
with month = 5 and month = 13.
2. Create a switch statement that takes a letter grade (A, B, C, D, F) and outputs a
message like "Excellent" for A, "Good" for B, etc. Include a default case for invalid
grades.
Explanation
Loops allow repetitive execution of code. JavaScript provides three main loop types:
Example:
for (let i = 1; i <= 5; i++) {
console.log(i); // Output: 1, 2, 3, 4, 5
}
2. While Loop
Syntax:
while (condition) {
// Code to repeat
}
Example:
let count = 0;
while (count < 3) {
console.log("Count: " + count); // Output: Count: 0, Count: 1, Count: 2
count++;
}
3. Do...While Loop
Syntax:
do {
// Code to repeat
} while (condition);
Example:
let num = 0;
do {
console.log("Number: " + num); // Output: Number: 0
num++;
} while (num < 1);
Exercises
Part 3: Functions
Objective
Learn how to define and use functions to encapsulate reusable code in JavaScript.
Explanation
Functions are blocks of code designed to perform specific tasks. They can take parameters
(inputs), return values (outputs), and be reused throughout a program.
Syntax
// Code to execute
function greet(name) {
Exercises
1. Write a function isEven(num) that takes a number and returns true if it’s even, false
otherwise.
2. Create a function factorial(n) that calculates the factorial of a number (e.g., 5! = 5 × 4 × 3
× 2 × 1).
3. Define a function square(x) that returns the square of a number.
4. Write a function printNumbers(start, end) that prints all numbers between start and end
(inclusive) using a for loop.