Control Flow
Control flow determines the order in
which statements are executed in a program. JavaScript provides several
structures to make decisions and repeat actions.
Conditional
Statements: if, else, else if
Conditional statements let you run
code only if certain conditions are met.
let
age = 20;
if
(age < 18) {
console.log("You are a minor.");
}
else if (age >= 18 && age < 65) {
console.log("You are an adult.");
}
else {
console.log("You are a senior.");
}
switch Statement
The switch statement is used when you need to compare a value against
multiple possible matches.
let
day = "Monday";
switch
(day) {
case "Monday":
console.log("Start of the week!");
break;
case "Friday":
console.log("Almost weekend!");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Midweek day.");
}
Loops:
for, while, do...while
Loops let you execute code
repeatedly while a condition is true.
For Loop – repeats code a specific number of times:
for
(let i = 1; i <= 5; i++) {
console.log(i);
}
While Loop – runs as long as the condition is true:
let
i = 1;
while
(i <= 5) {
console.log(i);
i++;
}
Do...While Loop – runs the code at least once, then repeats while the
condition is true:
let
i = 1;
do
{
console.log(i);
i++;
}
while (i <= 5);
break and continue
- break
stops the loop entirely.
- continue
skips the current iteration and moves to the next.
for
(let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip number 3
}
if (i === 5) {
break; // Stop loop at 5
}
console.log(i);
}