Introduction To JavaScript Control Structures
In JavaScript, control structures are used to determine how your program flows — meaning which code runs and when. Two important control structures are:
Switch Case In JavaScript
What Is A Switch Case?
A switch case is used when you want to check a single value against multiple possible options. It is often cleaner and easier to read than using many if...else statements.
How It Works
switch takes an expression (a value).case.break keyword stops further checking.default case runs (optional).Basic Syntax
switch (expression) {
case value1:
// code to run if expression === value1
break;
case value2:
// code to run if expression === value2
break;
default:
// code to run if no case matches
}
Example 1: Simple Switch Case
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}
Output:
Wednesday
Why Break Is Important
If you forget break, JavaScript will continue executing the next cases even after a match.
Example without break:
let fruit = "apple";
switch (fruit) {
case "apple":
console.log("This is an apple");
case "banana":
console.log("This is a banana");
default:
console.log("Unknown fruit");
}
Output:
This is an apple This is a banana Unknown fruit
This behavior is called fall-through.
While Loop In JavaScript
What Is A While Loop?
A while loop is used to repeat a block of code as long as a condition remains true.
How It Works
true, the code runs.false.Basic Syntax
while (condition) {
// code to execute repeatedly
}
Example 1: Counting Numbers
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
Output:
1 2 3 4 5
Important Concept: Avoid Infinite Loops
If the condition never becomes false, the loop will run forever. This is called an infinite loop.
Example of an infinite loop:
let i = 1;
while (i <= 5) {
console.log(i);
// missing i++ causes infinite loop
}
To avoid this, always make sure the loop variable changes.
Combining Switch Case And While Loop
You can use both together to create more powerful programs.
Example: Menu System
let option = 1;
while (option <= 3) {
switch (option) {
case 1:
console.log("Option 1 selected");
break;
case 2:
console.log("Option 2 selected");
break;
case 3:
console.log("Option 3 selected");
break;
default:
console.log("Invalid option");
}
option++;
}
Output:
Option 1 selected
Option 2 selected
Option 3 selected