JavaScript includes the for loop to execute a block of code repeatedly. It is one of the most commonly used loops in programming.
The for loop repeatedly executes a block of code until a specified condition becomes false.
It is commonly used for counting, displaying data, and traversing arrays.
A for loop contains three important parts:
0 1 2 3 4 5
| Part | Description |
|---|---|
| var i=0 | Initializes the counter |
| i<6 | Checks the condition |
| i++ | Increases counter by 1 |
1 2 3 4 5 6 7 8 9 10
The for loop is commonly used to access array elements.
20
21
22
23
24
A for loop can display multiple values stored in an array.
Aman
Ravi
Priya
Neha
A for loop can also count backwards.
10 9 8 7 6 5 4 3 2 1
If the condition never becomes false, the loop runs forever.
⚠ Avoid infinite loops because they can freeze the browser.
The break statement immediately stops the loop.
1 2 3 4 5
The continue statement skips the current iteration.
1 2 4 5
Initialization can be written outside the loop.
1 2 3 4 5
The condition can be controlled inside the loop using break.
1 2 3 4 5
Displaying attendance numbers of students.
| Part | Purpose |
|---|---|
| Initialization | Starting value |
| Condition | Controls loop execution |
| Iteration | Updates counter value |
| break | Stops loop |
| continue | Skips current iteration |
arr.length instead of fixed numbers.Which part of a for loop checks whether the loop should continue?