Control Structures in JavaScript
====================================
Control structures are used to control the flow of execution in your program —
deciding which blocks of code run and how often.
1. if, else if, else
----------------------
Used for conditional branching.
let marks = 85;
if (marks >= 90) {
[Link]("Grade: A");
} else if (marks >= 75) {
[Link]("Grade: B");
} else {
[Link]("Grade: C");
}
Output:
Grade: B
2. switch statement
--------------------
Used when there are multiple possible conditions for a single variable.
let day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Invalid day");
}
Output:
Wednesday
3. Ternary Operator
--------------------
A shorter way to write simple if-else statements.
let age = 20;
let result = (age >= 18) ? "Eligible to vote" : "Not eligible";
[Link](result);
Output:
Eligible to vote
4. Loops (for, while, do...while)
-----------------------------------
Used for repeating tasks.
for loop
---------
for (let i = 1; i <= 5; i++) {
[Link]("Number:", i);
}
while loop
-------------
let i = 1;
while (i <= 3) {
[Link]("Count:", i);
i++;
}
do...while loop
---------------
let num = 1;
do {
[Link]("Value:", num);
num++;
} while (num <= 3);
5. break and continue
---------------------
Used to control loop execution.
break – exits the loop early.
continue – skips the current iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // skip 3
}
if (i === 5) {
break; // stop loop at 5
}
[Link](i);
}
Output:
1
2
4