Home › Learn › JavaScript › Loops

for loops

Lesson 11 of 40. Repeat a block a counted number of times.

for (let i = 0; i < 5; i++) { ... } has three parts: a starting statement, a condition checked before every round, and a step run after every round. This one runs five times with i from 0 to 4. Counting down is for (let i = n; i > 0; i--).

A loop usually builds a result in a variable declared before it: start let total = 0;, add inside, use after. total += x is shorthand for total = total + x; i++ adds one.

let total = 0;
for (let n = 1; n <= 3; n++) {
  total += n;
}
console.log(total);   // 6

Your task

Write sumTo(n) returning 1 + 2 + ... + n with a loop (0 for n of 0), and countDown(n) returning the array [n, n-1, ..., 1], so countDown(3) is [3, 2, 1].

Hint 1

for (let i = 1; i <= n; i++) total += i;

Hint 2

for (let i = n; i >= 1; i--) result.push(i);

Show the solution
function sumTo(n) {
  let total = 0;
  for (let i = 1; i <= n; i++) {
    total += i;
  }
  return total;
}

function countDown(n) {
  const result = [];
  for (let i = n; i >= 1; i--) {
    result.push(i);
  }
  return result;
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.