JavaScript / JavaScript Control Structures

Breaking and Continuing in Loops

This tutorial will teach you how to use the 'break' and 'continue' statements in JavaScript to control loop execution. These statements provide flexibility and control over your l…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores conditionals, loops, and control flow in JavaScript.

1. Introduction

In this tutorial, we'll learn about two essential keywords in JavaScript that help control loop execution: break and continue. These keywords provide the flexibility to jump out of loops or skip iterations, making your code more efficient and readable.

By the end of the tutorial, you should be able to:
- Understand the purpose and usage of the break and continue statements
- Implement these statements in your JavaScript code

Before you start, you should be familiar with the basics of JavaScript, including variables, data types, and loops.

2. Step-by-Step Guide

The break statement

The break statement is used to exit from a loop early, stopping its execution completely. As soon as the JavaScript engine encounters a break statement, it jumps out of the current loop and continues executing the code that follows.

Here's a simple example:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break;
  }
  console.log(i);
}

In this code, the loop will only print numbers from 0 to 4. As soon as i equals 5, the break statement is executed, and the loop is terminated.

The continue statement

The continue statement, on the other hand, doesn't terminate the loop. Instead, it skips the current iteration and jumps to the next one.

Here's how you can use the continue statement:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    continue;
  }
  console.log(i);
}

In this example, the loop will print numbers from 0 to 9, but not 5. Once i equals 5, the continue statement is executed, the current iteration is skipped, and the loop continues with the next iteration.

3. Code Examples

Let's look at some practical examples to understand these concepts better.

Example 1: Using break

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] > 5) {
    break;
  }
  console.log(numbers[i]);
}

The output will be: 1 2 3 4 5
In this example, as soon as a number greater than 5 is encountered, the loop is terminated, and the program stops printing numbers.

Example 2: Using continue

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] === 5) {
    continue;
  }
  console.log(numbers[i]);
}

The output will be: 1 2 3 4 6 7 8 9 10
In this case, when the number 5 is encountered, the continue statement skips the current iteration, and the number 5 is not printed.

4. Summary

In this tutorial, we learned how to use the break and continue statements in JavaScript. The break statement allows us to exit a loop prematurely, while the continue statement lets us skip an iteration. Both are powerful tools for controlling loop execution and can lead to more efficient and readable code.

For further study, consider exploring nested loops and how break and continue work within them. For additional resources, the Mozilla Developer Network provides comprehensive documentation on JavaScript.

5. Practice Exercises

  1. Write a program that prints numbers from 1 to 10, but stops printing as soon as it encounters a number divisible by 7.
  2. Write a program that prints numbers from 1 to 20, but skips any number that's divisible by 3 or 5.
  3. Write a program that loops through the array ["Apple", "Banana", "Cherry", "Date", "Elderberry"] and stops as soon as it encounters a fruit starting with 'D'.

For each exercise, try to solve it first, then check the solutions below.

Solutions

  1. Solution:
for (let i = 1; i <= 10; i++) {
  if (i % 7 === 0) {
    break;
  }
  console.log(i);
}
  1. Solution:
for (let i = 1; i <= 20; i++) {
  if (i % 3 === 0 || i % 5 === 0) {
    continue;
  }
  console.log(i);
}
  1. Solution:
let fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];
for (let i = 0; i < fruits.length; i++) {
  if (fruits[i].startsWith('D')) {
    break;
  }
  console.log(fruits[i]);
}

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Backlink Checker

Analyze and validate backlinks.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help