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

  1. for

  2. while

  3. do...while

  4. for...in

  5. for...of


1️⃣ for Loop

Used when you know how many times you want to repeat.



 

📝 Output:

1
2
3
4
5

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:

name: John
age: 25
city: Delhi

5️⃣ for…of Loop

Used to loop through arrays or strings.


 

Output:

red
green
blue

📌 Example with HTML Output


 

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

🏁 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

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *