SimpleTuts.com

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:

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:


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:


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

  1. User enters a number.
  2. When the button is clicked, the function generateTable() runs.
  3. A for loop runs from 1 to 10.
  4. 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:

Output:


8. What Students Learned


Next Chapter

Chapter 5: Functions in JavaScript with Real-Life Example: Simple Calculator Application