chap loop pdf
chap loop pdf
A for loop in JavaScript is used to repeat a block of code a certain number of times. It's ideal
when you know in advance how many times the loop should run.
Basic Syntax:
javascript
Copy code
// Code to be executed
Breakdown:
Initialization: This step runs once before the loop starts. It's often used to declare and initialize a
loop counter, like let i = 0;.
Condition: Before each loop iteration, JavaScript checks this condition. If it's true, the code inside
the loop runs. If it's false, the loop stops.
Increment: After each iteration, this step is executed, often used to update the loop counter (e.g.,
i++).
Example:
javascript
Copy code
console.log(i);
}
This loop will output 0, 1, 2, 3, 4. It starts with i = 0, checks if i < 5, and increments i by 1 on each
iteration.
How it Works:
The process repeats until the condition becomes false (i.e., when i = 5).
Key Points:
javascript
Copy code
console.log(array[i]);
javascript
Copy code
console.log(i);
The `for` loop is one of the most commonly used loops in JavaScript. It is ideal when you know
how many times you want to execute a block of code.
#### **Syntax:**
```javascript
// Code to be executed
```
**Explanation of Syntax:**
1. **Initialization**: This is where you define and initialize your loop control variable. It usually
runs once at the beginning of the loop.
2. **Condition**: The loop runs as long as this condition is `true`. Once it becomes `false`, the
loop stops.
3. **Iteration**: This part updates the loop control variable (usually increments or decrements)
after each iteration.
---
### **Example:**
```javascript
console.log(i);
```
**Output:**
```
```
#### **Explanation:**
- **Initialization**: `let i = 1` sets the starting point for the loop, initializing `i` to 1.
- **Condition**: The loop runs as long as `i <= 5`. When `i` becomes greater than 5, the loop
stops.
- The code inside the loop (`console.log(i);`) is executed for each value of `i`.
---
1. **First iteration**:
- `i = 1`
2. **Second iteration**:
- `i = 2`
3. **Third iteration**:
- `i = 3`
4. **Fourth iteration**:
- `i = 4`
5. **Fifth iteration**:
- `i = 5`
6. **Termination**:
- `i = 6`
---
```javascript
console.log(colors[i]);
```
**Output:**
```
red
green
blue
```
```javascript
```
---
### **Conclusion:**
The `for` loop is perfect when you know how many times a loop should run. It lets you initialize,
set a condition, and increment a control variable all in one line, making it concise and easy to
control the flow of the loop.