In the previous article, we learned how conditional statements help programs make decisions. However, many situations require performing the same task repeatedly.
For example:
Display numbers from 1 to 100
Print multiplication tables
Process thousands of records
Generate reports
Display product lists
Writing the same statement repeatedly is inefficient. To solve this problem, JavaScript provides loops.
Loops allow a block of code to execute multiple times automatically.
In this article, we will learn:
What loops are
Why loops are needed
Types of loops
for loop
while loop
do-while loop
Nested loops
break statement
continue statement
Practical examples
Dry runs
What is a Loop?
A loop is a control structure that repeatedly executes a block of code until a specified condition becomes false.
Basic concept:
Condition True
↓
Execute Code
↓
Check Condition Again
↓
Repeat
Why Loops are Needed
Without loops:
document.write("Hello<br>");
document.write("Hello<br>");
document.write("Hello<br>");
document.write("Hello<br>");
document.write("Hello<br>");
This approach becomes impractical for large repetitions.
Using loops:
for(let i=1; i<=5; i++)
{
document.write("Hello<br>");
}
Output remains the same with much less code.
Types of Loops in JavaScript
JavaScript provides:
| Loop Type | Purpose |
|---|---|
| for | Known number of repetitions |
| while | Unknown repetitions |
| do-while | Execute at least once |
| Nested Loop | Loop inside loop |
The for Loop
The for loop is the most commonly used loop.
It is preferred when the number of repetitions is known.
Syntax
for(initialization;
condition;
update)
{
statements;
}
Components of a for Loop
for(let i=1;
i<=5;
i++)
| Part | Purpose |
|---|---|
| Initialization | Start value |
| Condition | Check repetition |
| Update | Increase or decrease value |
Example 1 – Print Numbers 1 to 5
for(let i=1; i<=5; i++)
{
document.write(i + "<br>");
}
Output:
1
2
3
4
5
Dry Run
i = 1
1 <= 5 → true
Print 1
i++
i = 2
2 <= 5 → true
Print 2
...
i = 6
6 <= 5 → false
Loop stops
Example 2 – Print Numbers 1 to 10
for(let i=1; i<=10; i++)
{
document.write(i + "<br>");
}
Example 3 – Reverse Counting
for(let i=10; i>=1; i--)
{
document.write(i + "<br>");
}
Output:
10
9
8
7
6
5
4
3
2
1
Example 4 – Print Even Numbers
for(let i=2; i<=20; i+=2)
{
document.write(i + "<br>");
}
Output:
2
4
6
8
10
12
14
16
18
20
Example 5 – Print Odd Numbers
for(let i=1; i<=19; i+=2)
{
document.write(i + "<br>");
}
Output:
1
3
5
7
9
11
13
15
17
19
Multiplication Table Program
let num = 5;
for(let i=1; i<=10; i++)
{
document.write(
num + " × " +
i + " = " +
(num*i)
);
document.write("<br>");
}
Output:
5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
...
5 × 10 = 50
Sum of Numbers 1 to 10
let sum = 0;
for(let i=1; i<=10; i++)
{
sum += i;
}
document.write(sum);
Output:
55
Dry Run
sum = 0
sum = 0 + 1 = 1
sum = 1 + 2 = 3
sum = 3 + 3 = 6
...
sum = 55
The while Loop
The while loop executes as long as the condition remains true.
Syntax
while(condition)
{
statements;
}
Example
let i = 1;
while(i <= 5)
{
document.write(i + "<br>");
i++;
}
Output:
1
2
3
4
5
Dry Run
i = 1
1 <= 5
Print 1
i++
i = 2
Repeat
Reverse Counting Using while
let i = 10;
while(i >= 1)
{
document.write(i + "<br>");
i--;
}
Infinite Loop Example
Wrong:
let i = 1;
while(i <= 5)
{
document.write(i);
}
Problem:
i never changes
Result:
Infinite Loop
Browser may freeze.
The do-while Loop
The do-while loop executes at least once.
Syntax
do
{
statements;
}
while(condition);
Example
let i = 1;
do
{
document.write(i + "<br>");
i++;
}
while(i <= 5);
Output:
1
2
3
4
5
Difference Between while and do-while
while
Condition checked first.
while(condition)
{
}
do-while
Code executes first.
do
{
}
while(condition);
Example
let i = 10;
do
{
document.write(i);
}
while(i < 5);
Output:
10
Even though condition is false.
Comparison of Loops
| Feature | for | while | do-while |
|---|---|---|---|
| Initialization | Included | Separate | Separate |
| Condition Check | Before | Before | After |
| Executes At Least Once | No | No | Yes |
Nested Loops
A loop inside another loop.
Syntax
for(...)
{
for(...)
{
}
}
Example
for(let i=1; i<=3; i++)
{
for(let j=1; j<=3; j++)
{
document.write(j);
}
document.write("<br>");
}
Output:
123
123
123
Star Pattern Program
for(let i=1; i<=5; i++)
{
for(let j=1; j<=i; j++)
{
document.write("*");
}
document.write("<br>");
}
Output:
*
**
***
****
*****
Dry Run
i=1 → *
i=2 → **
i=3 → ***
i=4 → ****
i=5 → *****
break Statement
Used to terminate a loop immediately.
Example
for(let i=1; i<=10; i++)
{
if(i==5)
{
break;
}
document.write(i);
}
Output:
1234
Loop stops when i becomes 5.
continue Statement
Skips current iteration.
Example
for(let i=1; i<=5; i++)
{
if(i==3)
{
continue;
}
document.write(i);
}
Output:
1245
3 is skipped.
Real-Life Example – Password Attempts
for(let attempt=1;
attempt<=3;
attempt++)
{
document.write(
"Attempt " + attempt
);
document.write("<br>");
}
Output:
Attempt 1
Attempt 2
Attempt 3
Complete Practical Program
<!DOCTYPE html>
<html>
<body>
<script>
document.write(
"Numbers 1 to 10"
);
document.write("<br>");
for(let i=1; i<=10; i++)
{
document.write(i);
document.write("<br>");
}
</script>
</body>
</html>
Flowchart of a Loop
Start
│
▼
Initialize
│
▼
Check Condition
│
┌─────┴─────┐
│ │
True False
│ │
Execute End
│
Update
│
└───────────►
Real-Life Applications
Loops are used in:
ATM systems
Banking software
Online shopping
Data processing
Games
Social media feeds
Student result systems
Companies like Google, Amazon, and Microsoft use loops extensively for handling massive amounts of data.
Common Mistakes Beginners Make
Missing Update Statement
Wrong:
while(i<=10)
{
}
Can create infinite loops.
Wrong Condition
for(let i=1; i>=10; i++)
Loop never executes.
Confusing break and continue
break→ Ends loopcontinue→ Skips iteration
Advantages of Loops
Reduce code repetition
Improve efficiency
Handle large datasets
Simplify complex tasks
Essential for programming
Conclusion
Loops are one of the most powerful features of JavaScript. They allow programs to repeat tasks efficiently and are essential for solving real-world problems.
Comments
Post a Comment