Foundations
Loops
Loops repeat a block while a counter changes.
for loop
A `for` loop can initialize a counter, test a condition, and update the counter after each pass.
Loops
loops.js
Replay: real traced execution (multi-file project)
const limit = 4;
let total = 0;
for (let number = 1; number <= limit; number++) {
total += number;
}
console.log("limit=" + limit);
console.log("total=" + total);
const limit = 2;
let total = 0;
for (let number = 1; number <= limit; number++) {
total += number;
}
console.log("limit=" + limit);
console.log("total=" + total);
const limit = 6;
let total = 0;
for (let number = 1; number <= limit; number++) {
total += number;
}
console.log("limit=" + limit);
console.log("total=" + total);
limit ← 4, total ← 0
1const limit→ 4 = 4; //@limit=2, 62let total→ 0 = 0;total ← 1
pass 1 of 41const limit = 4; //@limit=2, 62let total = 0;34for (let number1 = 1; number <= limit4; number++) {5 total += number1;6}values this step1totalAll 4 passes — pass 1 is the card above pass numbertotal1 1 1 2 2 3 3 3 6 4 4 10 console.log("limit=" + limit);
5 total += number;6}78console.log("limit=" + limit4);9console.log("total=" + total10);outputlimit=4 total=10
limit ← 2, total ← 0
1const limit→ 2 = 2;2let total→ 0 = 0;total ← 1
pass 1 of 21const limit = 2;2let total = 0;34for (let number1 = 1; number <= limit2; number++) {5 total += number1;6}values this step1totaltotal ← 3
pass 2 of 21const limit = 2;2let total = 0;34for (let number2 = 1; number <= limit2; number++) {5 total += number2;6}values this step3totalconsole.log("limit=" + limit);
5 total += number;6}78console.log("limit=" + limit2);9console.log("total=" + total3);outputlimit=2 total=3
limit ← 6, total ← 0
1const limit→ 6 = 6;2let total→ 0 = 0;total ← 1
pass 1 of 61const limit = 6;2let total = 0;34for (let number1 = 1; number <= limit6; number++) {5 total += number1;6}values this step1totalAll 6 passes — pass 1 is the card above pass numbertotal1 1 1 2 2 3 3 3 6 4 4 10 5 5 15 6 6 21 console.log("limit=" + limit);
5 total += number;6}78console.log("limit=" + limit6);9console.log("total=" + total21);outputlimit=6 total=21
Follow the Loop
limitstarts at4.totalstarts at0.- The loop adds
1, then2, then3, then4. totalbecomes10.- The program prints
limit=4andtotal=10. | limit | numbers added | total | | --- | --- | --- | | 2 | 1, 2 | 3 | | 4 | 1, 2, 3, 4 | 10 | | 6 | 1, 2, 3, 4, 5, 6 | 21 |
Exercise: loops.js
Reproduce total=10 for limit 4, then try limit 2 and 6 and predict each total before running it.