JavaScript Loops
🔄 What Are JavaScript Loops?
Loops are used to repeat a block of code multiple times until a condition becomes false.
Example use cases:
-
Printing numbers
-
Iterating through arrays
-
Repeating tasks automatically
🧩 Types of Loops in JavaScript
-
for -
while -
do...while -
for...in -
for...of
1️⃣ for Loop
Used when you know how many times you want to repeat.
📝 Output:
2️⃣ while Loop
Runs as long as the condition is true.
3️⃣ do…while Loop
Runs the code at least once, even if the condition is false.
4️⃣ for…in Loop
Used to loop through objects.
Output:
5️⃣ for…of Loop
Used to loop through arrays or strings.
Output:
📌 Example with HTML Output
Output:
🏁 Summary Table
| Loop Type | Best Use |
|---|---|
for |
Known number of repetitions |
while |
Repeat until condition changes |
do...while |
Run at least once |
for...in |
Loop through object keys |
for...of |
Loop through array or string values |
