LESSON 10 · BEGINNER4 min read

Loops & Iteration

Repeat work with for, while, and do...while loops, control each pass, and iterate text and arrays safely.

ES2024 / Node.js 20+Free to readModule 2 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Write for, while, and do...while loops with clear stopping conditions.
  • Use break and continue without hiding the loop's main rule.
  • Trace nested loops and state an invariant for a running calculation.
  • Choose the loop form that matches the data and the task.

01A for loop repeats a known count

A for loop repeats a block a known number of times. Its header has three parts: initialize a counter, state the condition that keeps the loop running, and update the counter. The counter declared with let belongs to the loop's block.

Trace the loop by writing down the counter and the accumulated value after each pass. For a sum from 1 to 5, the total grows by one more each time. When the condition becomes false, execution continues after the loop. Predict the number of passes from the condition before running the program.

sum.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02while and do...while wait for a condition

A while loop checks its condition before each pass. Use it when the number of repetitions is unknown, such as reading until a value changes. A do...while loop runs its body once before checking, which is useful when at least one attempt must happen.

Every loop needs a path to termination. Update the variable used in the condition, or change the state that makes the condition false. If the condition never becomes false, the program hangs. In a browser, that can freeze the page; in Node.js, it blocks the process. When a loop misbehaves, print the counter and the condition during development instead of guessing.

countdown.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03break leaves early; continue skips a pass

break leaves the nearest loop immediately. continue skips the rest of the current pass and starts the next one. Use them when they express the rule more clearly than another nested condition. Overusing them can make the flow hard to follow.

In the example, scores below 70 are skipped, and the loop stops at the first score of 90 or more. That combines filtering with an early exit. Ask whether the loop should stop or merely skip before choosing break versus continue.

scores.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04Nested loops multiply the work

A nested loop places one loop inside another. The inner loop completes all of its passes for each pass of the outer loop. This is useful for tables and combinations, but the work multiplies: three outer passes times three inner passes means nine iterations.

A loop invariant is a statement that should be true before and after every pass. For a running total, the invariant is that total holds the sum of everything processed so far. Naming that fact helps you check the update step and catch off-by-one errors.

table.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

05Iterate values and choose the right loop

for...of reads each value from a string or array without managing an index. Use it when you need the values themselves. Use a classic for loop when you need the index, need to skip items, or need to iterate in reverse.

Choose the simplest loop that matches the task: a for loop for a known count, while for an unknown number of attempts, do...while when one attempt is mandatory, and for...of for values. Write the stopping condition first, then the body. That order prevents many infinite loops.

vowels.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • Choose the loop form from the task: known count, unknown attempts, at least one pass, or values from a collection.
  • Every loop needs a condition that can become false and an update that moves it toward that point.
  • break exits a loop, continue skips a pass, and nested loops multiply the number of iterations.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Sum the even numbers

Use a for loop to add every even number from 1 through 20 and print the total. Do not write the even numbers by hand.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
let sum = 0;for (let n = 1; n <= 20; n++) {  if (n % 2 === 0) {    sum += n;  }}console.log(sum);

The remainder check identifies even values. The loop adds 2, 4, 6, and so on through 20, producing 110.

02

Exercise 2: Find the first long word

Given words = ["sun", "javascript", "code", "learning"], loop through the array and stop at the first word longer than six characters. Print Found: followed by the word, then print Checked: followed by how many words were examined.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
const words = ["sun", "javascript", "code", "learning"];let checked = 0;for (const word of words) {  checked++;  if (word.length > 6) {    console.log(`Found: ${word}`);    break;  }}console.log(`Checked: ${checked}`);

The loop checks sun and then javascript, which is ten characters long. break stops the loop before the remaining words, and checked reports 2.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01How many times does for (let i = 0; i < 4; i++) run its body?
02What is the defining behavior of a do...while loop?
03Which statement skips the rest of the current pass but keeps looping?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Sum the even numbers

Use a for loop to add every even number from 1 through 20 and print the total. Do not write the even numbers by hand.

EXPECTED OUTPUT
110
main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.