Javascript

08 For Loop

Here are five examples of `for` loops in JavaScript, ranging from easy to hard, with output displayed directly in the browser using `document.write`.


 

---


 

### 1. **Basic For Loop** - Easy
```javascript
document.write("<h3>Basic For Loop</h3>");
for (let i = 1; i <= 5; i++) {
    document.write("Number: " + i + "<br>");
}
```


 

---


 

### 2. **For Loop to Sum Numbers** - Easy
```javascript
document.write("<h3>For Loop to Sum Numbers</h3>");
let sum = 0;
for (let i = 1; i <= 5; i++) {
    sum += i;
}
document.write("Sum of numbers from 1 to 5 is: " + sum);
```


 

---


 

### 3. **For Loop with Arrays** - Medium
```javascript
document.write("<h3>For Loop with Arrays</h3>");
let fruits = ["Apple", "Banana", "Cherry", "Date"];
for (let i = 0; i < fruits.length; i++) {
    document.write("Fruit " + (i + 1) + ": " + fruits[i] + "<br>");
}
```


 

---


 

### 4. **Nested For Loop** - Medium
```javascript
document.write("<h3>Nested For Loop</h3>");
for (let i = 1; i <= 3; i++) {
    for (let j = 1; j <= 3; j++) {
        document.write("Pair: (" + i + ", " + j + ")<br>");
    }
}
```


 

---


 

### 5. **For Loop with Condition** - Hard
```javascript
document.write("<h3>For Loop with Condition</h3>");
document.write("Odd numbers from 1 to 10:<br>");
for (let i = 1; i <= 10; i++) {
    if (i % 2 !== 0) {
        document.write(i + "<br>");
    }
}
```


 

---


 

Copy and paste these examples into an HTML file to see them displayed in your browser! 😊
2 min read
Nov 19, 2024
By Md Real
Share

Leave a comment

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

Related posts

Nov 19, 2024 • 2 min read
06 If Else Statement
Nov 19, 2024 • 2 min read
03 Js Variable
Nov 19, 2024 • 2 min read
02 Js Comment