Loops and Iteration

Beginner
80 XP
30 min
Lesson Content

Loops and Iteration

Loops let your code repeat actions without writing the same lines again and again.

Common Loop Types

  • for — when you know how many times to run
  • while — when you run until a condition changes
  • for...of — to iterate collections like arrays

Why use loops?

Loops save time and make your programs flexible — they handle lists, process data, and automate repetitive tasks.

Quick examples

// for loop
for (let i = 1; i <= 5; i++) {
  console.log(i);
}

// while loop
let n = 1;
while (n <= 3) {
  console.log('count', n);
  n++;
}

// for...of with arrays
const fruits = ['apple', 'banana', 'cherry'];
for (const f of fruits) {
  console.log(f);
}
Example Code

Use a loop to compute the sum of numbers 1 through 10 and print the result.

// Sum numbers from 1 to 10
let sum = 0;
// TODO: use a loop to add numbers 1..10 to sum
console.log('Sum is:', sum);

Expected Output:

Sum is: 55
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code