Loops in JavaScript
Understanding Loops in JavaScript
1. What are Loops?
Loops are used when we want to repeat a block of code multiple times.
Real-life examples:
- Displaying numbers from 1 to 10
- Printing multiplication tables
- Processing multiple student records
Instead of writing the same code again and again, loops allow us to automate repetition.
2. The for Loop
The for loop is the most commonly used loop when we know how many times the loop should run.
Syntax:
for(initialization; condition; increment){
// code to execute
}
Example:
for(let i = 1; i <= 5; i++){
console.log(i);
}
Output:
1
2
3
4
5
Explanation:
i = 1→ starting valuei <= 5→ loop runs until 5i++→ increase value each time
3. The while Loop
The while loop runs as long as the condition is true.
let i = 1;
while(i <= 5){
console.log(i);
i++;
}
Explanation:
- The loop continues while
i <= 5 i++increases the value
4. The do...while Loop
The do...while loop executes the code at least once, even if the condition is false.
let i = 1;
do{
console.log(i);
i++;
}
while(i <= 5);
5. Real-Life Example: Multiplication Table Generator
This application generates a multiplication table for a number entered by the user.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Multiplication Table</title>
</head>
<body>
<h2>Multiplication Table Generator</h2>
<input type="number" id="number" placeholder="Enter a number">
<button onclick="generateTable()">Generate Table</button>
<div id="result"></div>
<script src="app.js"></script>
</body>
</html>
Run Code
app.js
function generateTable(){
let num = Number(document.getElementById("number").value);
let result = document.getElementById("result");
result.innerHTML = "";
for(let i = 1; i <= 10; i++){
result.innerHTML += num + " x " + i + " = " + (num * i) + "<br>";
}
}
Run Code
6. How This Example Works
- User enters a number.
- When the button is clicked, the function
generateTable()runs. - A for loop runs from 1 to 10.
- Each multiplication result is displayed on the webpage.
Example output for input 5:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 10 = 50
7. Practice Exercise
Create a Number List Generator.
Input:
- A number (N)
Output:
- Display numbers from 1 to N using a loop.
8. What Students Learned
forloopswhileloopsdo...whileloops- How to repeat tasks automatically
- Building a real interactive example using loops
Next Chapter
Chapter 5: Functions in JavaScript with Real-Life Example: Simple Calculator Application