When the number of repetitions is clear, a for loop is often easier to read than a while loop. It expresses “take values from a sequence one by one” in a single line.
Counting with for
A JavaScript counting loop places initialization, continuation condition, and update in one header, such as for (let i = 0; i < 5; i++).
for (let i = 0; i < 5; i++) {
console.log(i + " ");
}
console.log();
for (let i = 1; i < 10; i += 2) {
console.log(i + " ");
}Output:
0 1 2 3 4
10 11 12 13 14
1 3 5 7 9for (initialization; condition; update) initializes once, checks the condition before each iteration, and updates after each iteration.
KNOWLEDGE QUIZ
Fixed-count accumulation
To sum integers from 1 to 100, use for (let i = 1; i <= 100; i++). The condition i <= 100 includes 100.
let total = 0;
for (let i = 1; i <= 100; i++) {
total += i;
}
console.log(total);Output:
Sum = 5050This version makes the value range of i easier to see than an equivalent while loop.
Step through an accumulating for loop
Run one statement at a time and watch i flow into total.
01let total = 0;02for (let i = 1; i <= 100; i++) {03 total += i;04}05console.log(total);
>>>
KNOWLEDGE QUIZ
Fibonacci sequence
The first two Fibonacci numbers are 1, 1. Starting from the third term, each term equals the sum of the previous two terms.
let n = 10;
let first = 1;
let second = 1;
console.log(first + " " + second + " ");
for (let i = 3; i <= n; i++) {
let current = first + second;
console.log(current + " ");
first = second;
second = current;
}One possible run:
Enter the number of terms: 10
1 1 2 3 5 8 13 21 34 55The most important updates are:
first = second;
second = current;They slide the two-number window forward, so the next loop can keep using the previous two terms.
Slide the Fibonacci window
Each click executes the next assignment. Notice that assignment order matters.
01let first = 1;02let second = 1;03for (let i = 3; i <= 10; i++) {04 let current = first + second;05 first = second;06 second = current;07}
KNOWLEDGE QUIZ
List the leap years in a range
Read a start year and end year, then use a for loop to find every leap year in the interval.
- Read startYear and endYear.
- Iterate over the closed interval and test each year.
- Print all leap years on one line.