Control Flow in JavaScript refers to the order in which code is executed.
By default, JavaScript runs code from top to bottom, but control flow statements let you:
if, else)switch)break, return, continue)if (condition) {
// code runs if condition is true
} else if (anotherCondition) {
// code runs if anotherCondition is true
} else {
// code runs if none of the above are true
}let age = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}The switch statement is used to handle multiple conditions more cleanly than many else ifs.
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default code block
}let color = "blue";
switch (color) {
case "red":
console.log("Stop!");
break;
case "yellow":
console.log("Get ready!");
break;
case "green":
console.log("Go!");
break;
default:
console.log("Unknown color");
}Loops let you run a block of code repeatedly, either a set number of times or until a condition is false.
Use when you know how many times to loop.
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}Runs while a condition is true.
let i = 1;
while (i <= 3) {
console.log("While loop:", i);
i++;
}Runs at least once, even if the condition is false.
let i = 1;
do {
console.log("Do-While:", i);
i++;
} while (i <= 3);Used to iterate over arrays or iterable objects.
let fruits = ["apple", "banana", "mango"];
for (let fruit of fruits) {
console.log(fruit);
}Used to iterate over object properties.
let person = { name: "Sam", age: 25 };
for (let key in person) {
console.log(key, "=", person[key]);
}Exits the current loop or switch early.
for (let i = 1; i <= 5; i++) {
if (i === 3) break;
console.log(i); // Output: 1, 2
}Skips the current iteration and continues with the next one.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i); // Output: 1, 2, 4, 5
}Ends function execution and returns a value (covered more in functions chapter).
function multiply(a, b) {
return a * b;
}| Control Type | Statement | Purpose |
|---|---|---|
| Decision | if, else | Run code conditionally |
| Multi-condition | switch | Cleaner alternative to many ifs |
| Repetition | for, while | Repeat code while condition holds |
| Break flow | break | Exit loop/switch early |
| Skip iteration | continue | Skip current loop iteration |
| Exit function | return | Return value from function |
Write a script that checks a number and prints:
let num = 15;
if (num % 3 === 0 && num % 5 === 0) {
console.log("FizzBuzz");
} else if (num % 3 === 0) {
console.log("Fizz");
} else if (num % 5 === 0) {
console.log("Buzz");
} else {
console.log(num);
}