Loops repeat a block while a counter changes.

Loops

loops.js
const limit = 4;
let total = 0;

for (let number = 1; number <= limit; number++) {
  total += number;
}

console.log("limit=" + limit);
console.log("total=" + total);

Follow the Loop

  1. limit starts at 4.
  2. total starts at 0.
  3. The loop adds 1, then 2, then 3, then 4.
  4. total becomes 10.
  5. The program prints limit=4 and total=10. | limit | numbers added | total | | --- | --- | --- | | 2 | 1, 2 | 3 | | 4 | 1, 2, 3, 4 | 10 | | 6 | 1, 2, 3, 4, 5, 6 | 21 |
for loop A `for` loop can initialize a counter, test a condition, and update the counter after each pass.

Exercise: loops.js

Reproduce total=10 for limit 4, then try limit 2 and 6 and predict each total before running it.