JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 4: Repetition and Problem-SolvingLesson 18 of 150About 35 minutes

Lesson 18: Break and continue

01Opening question

You are searching 10,000 orders for one order number. Once you find it, should the loop keep checking the rest?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Remove break and run again. Count how many orders are checked.

const orders = ["A10", "B22", "C31", "D45"];
for (const id of orders) {
  console.log("Checking", id);
  if (id === "B22") {
    console.log("Found it");
    break;
  }
}

03Objective and prerequisites

Learning objective: Use break to leave a loop early and continue to skip one iteration, and decide when a flag or condition is clearer.

You need: Lesson 16: For loops, Lesson 17: While and do-while loops

Skills practised: Loops, break and continue.

04Explanation

break stops the loop immediately. The program continues with the first line after the loop.

continue skips the rest of the current iteration and jumps to the next one. In a for loop the update still runs.

Use break when you have found what you need (a search) or when continuing would be wrong (an error). Use continue to skip items that do not apply, such as empty lines or cancelled orders.

Both only affect the innermost loop they are in.

05Definitions

break
Leaves the current loop immediately.
continue
Skips the rest of the current iteration and moves to the next.
Early exit
Stopping a loop as soon as the answer is known.
Flag
A boolean variable that records whether something happened.
Guard clause
A check at the start of a block that skips or exits when the input does not apply.

Open the full glossary

06Visual learning object

Loop control tracker. Step through break and continue and see which lines are skipped.

Loading the interactive object…

Open the full While-loop visualizer page with its guided experiment.

07Examples

ex-018-01break ends a search Browser-executable JavaScript

Once the item is found there is no need to look further.

const stock = [12, 0, 7, 0, 3];
let firstEmpty = -1;
for (let i = 0; i < stock.length; i++) {
  if (stock[i] === 0) {
    firstEmpty = i;
    break;
  }
}
console.log("First empty shelf:", firstEmpty);
Sample input
None
Expected output
First empty shelf: 1
Common mistake
Forgetting break, which reports the last empty shelf (3) instead.
Try this
Find the first shelf with fewer than 5 items.
Source
examples/ex-018-01-break-search.js (repository pending publication)

ex-018-02continue skips items Browser-executable JavaScript

Cancelled orders are skipped without nesting the rest of the body.

const orders = [
  { id: 1, status: "paid", total: 20 },
  { id: 2, status: "cancelled", total: 50 },
  { id: 3, status: "paid", total: 15 }
];
let revenue = 0;
for (const order of orders) {
  if (order.status === "cancelled") continue;
  revenue += order.total;
}
console.log("Revenue:", revenue);
Sample input
None
Expected output
Revenue: 35
Common mistake
Using break instead of continue and stopping at the first cancelled order.
Try this
Also skip orders with a total under 16.
Source
examples/ex-018-02-continue-skip.js (repository pending publication)

ex-018-03continue in a counting loop Browser-executable JavaScript

The update i++ still runs after continue.

let line = "";
for (let i = 1; i <= 9; i++) {
  if (i % 2 === 0) continue;
  line += i + " ";
}
console.log(line.trim());
Sample input
None
Expected output
1 3 5 7 9
Common mistake
Thinking continue restarts the loop from the beginning.
Try this
Skip multiples of 3 instead.
Source
examples/ex-018-03-odd-numbers.js (repository pending publication)

ex-018-04A flag instead of break Browser-executable JavaScript

A condition in the loop header can replace break.

const temps = [18, 21, 26, 30];
let i = 0;
let found = false;
while (i < temps.length && !found) {
  found = temps[i] > 25;
  i++;
}
console.log(found, "at index", i - 1);
Sample input
None
Expected output
true at index 2
Common mistake
Forgetting that i was incremented after the match.
Try this
Rewrite with a for loop and break, then compare readability.
Source
examples/ex-018-04-flag-alternative.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Stop at the first match

Add break so a search reports the first match.

const names = ["Ana", "Ben", "Bea", "Cal"];
let match = "";
for (const name of names) {
  if (name.startsWith("B")) {
    match = name;
  }
}
console.log("First B name:", match);

Skip blank lines

Use continue as a guard clause.

const lines = ["milk", "", "eggs", "   ", "bread"];
let count = 0;
for (const line of lines) {
  // TODO: skip blank lines with continue
  count++;
  console.log(count + ". " + line.trim());
}

Fill the cart within budget

Combine continue and break in one loop.

const items = [
  { name: "Lamp", price: 30, inStock: true },
  { name: "Rug", price: 45, inStock: false },
  { name: "Chair", price: 40, inStock: true },
  { name: "Desk", price: 90, inStock: true },
  { name: "Plant", price: 10, inStock: true }
];
const BUDGET = 100;

09Prediction

Commit to an answer first, then run the real code to compare.

let s = "";
for (let i = 1; i <= 6; i++) {
  if (i === 2) continue;
  if (i === 5) break;
  s += i;
}
console.log(s);

What is printed?

10Debugging investigation

The sales report stops at a cancelled order

The daily revenue is far too low. Orders after the first cancelled one are never counted.

const orders = [
  { total: 40, cancelled: false },
  { total: 25, cancelled: true },
  { total: 30, cancelled: false },
  { total: 25, cancelled: false }
];
let revenue = 0;
for (const order of orders) {
  if (order.cancelled) break;
  revenue += order.total;
}
console.log("Revenue:", revenue);

More cases in the Debugging Detective Laboratory

11Practical scenario

Finding a booking

A help-desk tool searches today's bookings for a reference number. It stops at the match instead of scanning thousands of rows, and it skips cancelled bookings.

const bookings = ["R1", "R2", "R3"];
for (const ref of bookings) {
  if (ref === "R2") {
    console.log("Found", ref);
    break;
  }
}

12Knowledge check

1. What is printed?

for (let i = 0; i < 4; i++) {
  if (i === 2) break;
  console.log(i);
}
  • 0 1 2
  • 0 1
  • 0 1 2 3
  • Nothing

2. What does continue do?

  • Ends the loop
  • Skips to the next iteration
  • Restarts from the first iteration
  • Ends the program

3. How many lines are printed?

for (let i = 0; i < 4; i++) {
  if (i % 2 === 1) continue;
  console.log(i);
}
  • 4
  • 2
  • 3
  • 0

4. Why does this while loop never end?

let i = 0;
while (i < 3) {
  if (i === 1) continue;
  i++;
}
  • continue is not allowed in while
  • continue skips i++
  • The array is empty
  • while needs break

5. Which loop does break leave when loops are nested?

  • All loops
  • The innermost loop
  • The outermost loop
  • None

6. To skip invalid items, which is most readable?

  • Wrap the whole body in a big if
  • A continue guard clause at the top
  • Use break
  • Copy the loop

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Stop at the first match: Prints Ben; Uses break
  • Skip blank lines: Three numbered lines; Uses continue
  • Fill the cart within budget: Prints the cart; total is 70; Uses continue and break
  • ex-018-01: output matches the documented expected output
  • ex-018-02: output matches the documented expected output
  • ex-018-03: output matches the documented expected output
  • ex-018-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-01-foundations/module-04-repetition-and-problem-solving/lesson-018-break-and-continue/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • break leaves the loop.
  • continue skips to the next iteration.
  • Use break when the answer is found; continue for items that do not apply.
  • Make sure a while loop still updates its counter before a continue.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation break and continue
Context: I am learning loop control.
Task: Explain break and continue with a search and a filter example.
Constraints: Beginner level.
Expected behaviour: I can say which to use.
Testing: Give me three situations to choose for.
Code prediction Loop control drill
Context: I know break and continue.
Task: Ask me to predict five loops that use them.
Constraints: Wait for answers.
Expected behaviour: Include one nested loop.
Testing: Explain any I miss with a trace.
Debugging Wrong match reported
Context: My search loop reports the last match instead of the first.
Task: Help me see why with questions.
Constraints: No direct answer.
Expected behaviour: I fix it myself.
Testing: Suggest a log that shows each check.
Exercise generation Budget loops
Context: I finished the budget cart exercise.
Task: Create two exercises that need both continue and break.
Constraints: Fictional data, exact output.
Expected behaviour: Real shopping or booking contexts.
Testing: Include expected output.
Code review Control flow
Context: My loop has four break statements.
Task: Suggest a clearer structure.
Constraints: Keep behaviour identical.
Expected behaviour: At most one exit point.
Testing: Explain the trade-offs.