Overview
The for loop is the most basic way to repeat a process a specific number of times in a program. You create a variable as a counter, and the code inside the block continues to run as long as that variable meets a certain condition. This article explains the structure of the for loop, how to handle the loop variable correctly, and how to avoid infinite loops.
Specifications (Input/Output)
- Input: The number of times you want to repeat (the maximum value).
- Output: The value of the counter variable for each loop displayed in the console log.
Basic Usage
A for loop consists of three parts: (initialization; condition; final expression).
- Initialization: Runs once at the start (e.g., declaring a variable).
- Condition: Checked before each loop. If
true, the loop runs. Iffalse, the loop stops. - Final Expression: Runs at the end of each loop (e.g., increasing the variable).
Full Code (HTML / JavaScript)
HTML (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>for Loop Demo</title>
<script src="loop-demo.js" defer></script>
</head>
<body>
<div class="container">
<h1>Please check the Console</h1>
<p>The results of the repeating process are displayed in the console.</p>
</div>
</body>
</html>
JavaScript (loop-demo.js)
This is a basic pattern that starts from 0 and repeats the process 5 times. The variable i (short for iterator) is commonly used.
/**
* Repeating process using a for loop
* Outputs a log 5 times from 0 to 4.
*/
const runLoopDemo = () => {
console.log("--- Loop Start ---");
// let i = 0; -> Initialize the counter variable at 0
// i < 5; -> Repeat as long as i is less than 5 (0, 1, 2, 3, 4)
// i++; -> Increase i by 1 after each process
for (let i = 0; i < 5; i++) {
console.log(`Current count: ${i}`);
}
console.log("--- Loop End ---");
};
runLoopDemo();
Customization Points
- Changing the Start Value: If you start with
let i = 1, you can count using natural numbers (1, 2, 3…). In this case, you should adjust the condition toi <= 5(5 or less). - Step Size: If you change
i++toi += 2, the loop will skip numbers (0, 2, 4…). - Variable Scope: The variable
ideclared withletis only valid inside the{}block of theforloop. Trying to useioutside the loop will cause an error, which is good because it prevents variable conflicts.
Important Points
- Infinite Loops: If the condition is always
true(for example, ifinever decreases or the condition isi > -1), the browser will freeze. Always make sure your condition and final expression work together correctly. - Off-by-one Error: This is a mistake where you run the loop one time too many or too few. If you want to repeat 10 times and start from 0, use
< 10. If you start from 1, use<= 10.
Advanced Usage
Countdown (Reverse Loop)
By starting with a large value and decreasing it, you can create a countdown.
console.log("Starting countdown...");
// Start at 10, repeat while i is greater than 0, decrease by 1
for (let i = 10; i > 0; i--) {
console.log(`${i}...`);
}
console.log("Start!");
Summary
The for loop is the most basic syntax for repeating tasks a specific number of times.
- Declare the variable using
let. - Design the condition (using
<or<=) accurately. - Be careful to avoid infinite loops. Keep these points in mind when processing arrays or generating continuous data.
