JavaScript Loop For
The for
loop repeats code a specified number of times, or until a condition is met. It's commonly used to iterate over arrays or generate sequences of actions.
Key Topics
For Loop Basics
A for
loop has three parts in parentheses: initialization, condition, and increment/decrement expression.
for (let i = 0; i < 5; i++) {
console.log(i);
}
Output
> 0
> 1
> 2
> 3
> 4
Explanation: The loop runs as long as i < 5
, starting from 0 and incrementing by 1 each iteration.
Initialization, Condition, Increment
These three parts control the loop's start, continuation, and progression:
- Initialization:
let i = 0;
- Condition:
i < 5;
- Increment:
i++;
JavaScript Usage in DOM
This DOM-based example uses a for loop to list array elements in a paragraph.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>For Loop in DOM</title>
</head>
<body>
<h1>For Loop Demo</h1>
<button onclick="listItems()">List Items</button>
<p id="result"></p>
<script>
function listItems() {
let arr = ["A", "B", "C"];
let output = "";
for (let i = 0; i < arr.length; i++) {
output += arr[i] + " ";
}
document.getElementById("result").textContent = output;
}
</script>
</body>
</html>
Key Takeaways
- Control: A for loop uses initialization, condition, and increment steps.
- Iteration: Ideal for repeating actions or processing array elements.
- DOM Integration: Generate and display lists or multiple elements easily.