JavaScript Loops: while
and for
Loops are used to execute a block of code multiple times until a condition is met.
1️⃣ while
Loop
Repeats while a condition is true
.
Syntax
Example: Print numbers 1 to 5
📌 Output:
🔹 Explanation:
- Starts at
i = 1
- Runs until
i <= 5
becomesfalse
i++
increasesi
after each loop
2️⃣ do...while
Loop
Executes at least once, then repeats while the condition is true
.
Syntax
Example: Run at least once
📌 Output:
🔹 Explanation:
- Runs once, even though
num < 5
isfalse
- Useful when code should execute at least once
3️⃣ for
Loop
Repeats a fixed number of times.
Syntax
🔹 Breakdown:
initialization
→ Start the loopcondition
→ Run whiletrue
increment
→ Change variable each loop
Example: Print numbers 1 to 5
📌 Output:
4️⃣ for
vs. while
Feature | while Loop | for Loop |
---|---|---|
Use Case | When the number of iterations is unknown | When the number of iterations is known |
Structure | Condition only | Initialization, condition, increment in one line |
Example | while (x < 10) {...} | for (let i = 0; i < 10; i++) {...} |
5️⃣ for...of
Loop (For Arrays & Iterables)
Loops through values in an array.
📌 Output:
6️⃣ for...in
Loop (For Objects)
Loops through keys in an object.
📌 Output:
7️⃣ Loop Control: break
& continue
break
→ Stop the loop completely
📌 Output:
continue
→ Skip current iteration
📌 Output:
🎯 Summary
✅ while
→ Use when iterations are unknown
✅ do...while
→ Runs at least once
✅ for
→ Use when iterations are known
✅ for...of
→ Loop over arrays & iterables
✅ for...in
→ Loop over object properties
✅ break
→ Stop loop | continue
→ Skip iteration
🚀 Now you're ready to use loops in JavaScript! Let me know if you need help. 😊