Programs don’t just run from top to bottom — they often need to make decisions or repeat actions. This is called control flow, and it’s what makes code dynamic and useful.
In JavaScript, the two most common control flow tools are decisions (if/else) and loops (for, while).
🟢 Decisions with if/else
The if statement lets your program choose what to do based on a condition (something that is true or false).
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
- If the condition is true → run the first block.
- Otherwise → run the
elseblock.
👉 You can also add more options with else if:
let score = 85;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 75) {
console.log("Grade B");
} else {
console.log("Grade C");
}
🟡 Loops: Doing Things Repeatedly
Loops let you repeat the same action multiple times without writing it again and again.
For Loop
for (let i = 1; i <= 5; i++) {
console.log("Number: " + i);
}
- Starts at 1, ends at 5.
- Runs 5 times, printing numbers 1 to 5.
While Loop
let count = 1;
while (count <= 3) {
console.log("Count is " + count);
count++;
}
- Keeps running as long as the condition (
count <= 3) is true. - Don’t forget to update the counter (
count++), or the loop will never end!
Looping Through Arrays
Loops are especially useful with arrays:
let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
👉 Prints each fruit in the list.
✍️ Quick Practice
Try these in your browser console:
- Write an
if/elseprogram that checks if a number is positive or negative. - Use a
forloop to print numbers from 1 to 10. - Create an array of 3 hobbies and use a loop to print each one.
✨ Key Takeaways
- if/else helps your program make decisions.
- for and while loops help your program repeat actions.
- Loops are especially powerful when working with arrays.
👉 With decisions and loops, your programs can start reacting to conditions and handling repeated tasks automatically.