๐ Control Flow Statements in JavaScript
๐ Introduction
In JavaScript, control flow statements decide the order in which code runs. They help you make decisions (โ /โ), repeat tasks ๐, or exit early ๐ช. Think of them as traffic signals ๐ฆ guiding your programโs journey.
๐ง Major Control Flow Statements
- ๐ Conditional Statements โ if, if...else, switch
- ๐ Looping Statements โ for, while, do...while
- โน๏ธ Jump Statements โ break, continue, return
๐ Conditional Flow
Used to run different code based on conditions.
if...else Example
let age = 18;
if (age >= 18) {
console.log("Adult โ
");
} else {
console.log("Minor โ");
}switch Example
let fruit = "apple";
switch(fruit) {
case "apple":
console.log("๐ Apple selected");
break;
case "banana":
console.log("๐ Banana selected");
break;
default:
console.log("Unknown fruit โ");
}๐ Looping Flow
Loops help you repeat code until a condition is met.
Looping Statements Example
// for loop
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
// while loop
let x = 1;
while (x <= 3) {
console.log("x is", x);
x++;
}
// do...while loop
let y = 1;
do {
console.log("y is", y);
y++;
} while (y <= 2);๐ Jump Flow
These statements help you exit or skip parts of code.
Jump Statements Example
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // skips 3๏ธโฃ
}
if (i === 5) {
break; // stops loop at 5๏ธโฃ
}
console.log(i);
}
function greet(name) {
if (!name) {
return "No name provided โ";
}
return "Hello " + name + " ๐";
}โก Control Flow Overview
| Type | Statement | Purpose |
|---|---|---|
| Conditional | if, if...else, switch | Decision making |
| Looping | for, while, do...while | Repeat code |
| Jump | break, continue, return | Alter loop/exit function |
Note
๐ก Tip: Use for when you know the number of iterations, use while when looping until a condition, and do...while when you want to run at least once.
>>"Control flow is the steering wheel ๐ of your program โ without it, your code would just drive straight forever."