Loading
0x30Lesson 4 of 6

Repeat work with loops

Use for and while loops to repeat instructions without copying code.

12 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Use a for loop with a counter
  • Use while for condition-controlled repetition
  • Avoid infinite loops

A loop repeats a block of code. A for loop is handy when you know how a counter changes; a while loop repeats as long as a condition stays true.

count.js
for (let count = 1; count <= 3; count++) {
  console.log(count);
}
Output
1
2
3

The for loop has a start (let count = 1), a condition (count <= 3) and an update (count++). Make sure each pass moves the condition toward false.

Key takeaways

  • Loops save you from repeating copied lines.

  • A for loop combines initialization, condition and update.

  • Check that a loop can eventually stop.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write JavaScript

Write the program, run it against the test cases, and use the feedback to build your JavaScript skills.

Exercise 1

Sum to n

+25 XP

Read a positive whole number from input. Add every integer from 1 through that number, then print the sum.

  • Sum through 5
  • Sum through 10
main.js
Loading editor…

JavaScript runs in a sandboxed browser frame with a 1.5 second time limit. Input is available as the string variable input.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Did you like the lesson? 😆👍
Consider a donation to support our work: