π Day 4: Mastering Loops in JavaScript
Welcome to Day 4 of the challenge!
Today we unlock one of JavaScriptβs most powerful tools: loops β a way to make your code do more with less.
A loop in JavaScript is a control structure that allows you to execute a block of code repeatedly as long as a specified condition is true.
Instead of writing repetitive code manually, loops help you automate tasks β like printing numbers, processing items in a list, or checking for conditions.
π Why Loops?
Imagine you were asked to print numbers from 1 to 100.
Would you really write:
console.log(1);
console.log(2);
console.log(3);
// ...
console.log(100);
No way!
Instead, we use loops to repeat actions efficiently.
π The 3 Main Loops in JavaScript
β
1. for loop
Great when you know how many times to repeat.
for (let i = 1; i <= 5; i++) {
console.log("Step:", i);
}
β
2. while loop
Used when you want to repeat while a condition is true.
let i = 1;
while (i <= 5) {
console.log("While Step:", i);
i++;
}
β
3. do...while loop
Runs at least once, even if the condition is false.
let i = 6;
do {
console.log("Do-While Step:", i);
i++;
} while (i <= 5);
β break and continue
β
break β exits the loop immediately
for (let i = 1; i <= 10; i++) {
if (i === 5) break;
console.log(i); // Stops at 4
}
β
continue β skips current iteration
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i); // Skips 3
}
β Mini Task:
Print All Even Numbers from 1 to 50
Your challenge: Loop from 1 to 50 and print only even numbers.
β
Solution 1 (for loop):
for (let i = 1; i <= 50; i++) {
if (i % 2 === 0) {
console.log(i);
}
}
β
Solution 2 (while loop):
let i = 2;
while (i <= 50) {
console.log(i);
i += 2;
}
β Interview Questions:
- Whatβs the difference between a for loop and a while loop?
- When would you prefer a do...while loop?
- What does break do inside a loop?
- What does continue do?
- Can you print numbers 1 to 100 using just one loop?
π― Thatβs a wrap for Day 4!
Tomorrow, in Day 5, weβll explore Functions & Scope β a major step toward writing cleaner, reusable code.
Keep learning. Keep building. πͺ
Top comments (0)