Featured
- Get link
- X
- Other Apps
🔂 Day 5 — Loops in JavaScript
🔂 Day 5 — Loops in JavaScript
Welcome to Day 5 🎉 — you’ve now learned how to make your program think with conditions, but what if you want to repeat a task **multiple times** automatically? That’s where **loops** come in! Loops let you run the same block of code until a condition is met — saving time, code, and effort.
🧩 1️⃣ What Are Loops?
A loop runs a section of code again and again until a certain condition becomes false. They help automate repetitive operations such as printing numbers, iterating arrays, or validating user input.
🔁 2️⃣ Types of Loops in JavaScript
1️⃣ for Loop
Used when you know how many times you want to run a block of code.
for (let i = 1; i <= 5; i++) {
console.log("Iteration:", i);
}
2️⃣ while Loop
Runs as long as the given condition is true.
let count = 1;
while (count <= 3) {
console.log("Count is:", count);
count++;
}
3️⃣ do...while Loop
Similar to while, but runs the code block **at least once**,
even if the condition is false initially.
let num = 1;
do {
console.log("Number:", num);
num++;
} while (num <= 3);
🎯 3️⃣ Loop Control Statements
break
Stops the loop entirely.
for (let i = 1; i <= 5; i++) {
if (i === 3) break;
console.log(i);
}
continue
Skips the current iteration and continues the next one.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i);
}
🔢 4️⃣ Nested Loops
A loop inside another loop — useful for grids or patterns.
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`i=${i}, j=${j}`);
}
}
🧮 5️⃣ Real Example: Sum of Numbers
let sum = 0;
for (let i = 1; i <= 5; i++) {
sum += i;
}
console.log("Total Sum:", sum);
🧠 6️⃣ Practice Task
- Print numbers from 1 to 10 using a
forloop. - Display even numbers up to 20 using
whileloop. - Use
do...whileto print numbers from 5 to 1. - Try using
breakto stop when the number reaches 7.
🎯 Summary
Loops are powerful for automation. Tomorrow, we’ll introduce **Functions and Scope**, where you’ll learn to organize your logic and reuse code efficiently.
Popular Posts
💙 Day 27: Bootstrap Mini Project – Responsive Portfolio Page
- Get link
- X
- Other Apps
🎨 Day 2: Headings, Paragraphs & Text Formatting
- Get link
- X
- Other Apps
Comments
Post a Comment