Register to get access to free programming courses with interactive exercises

Control statements JS: Arrays

There are two statements available for use in JavaScript loops that affect their behavior: break and continue. They're not strictly necessary, but they still occur in practice. Therefore, it's important to know about them.

Break

The break statement exits a loop. Not a function, a loop. When the interpreter encounters it, it stops executing the current loop and moves on to the instructions immediately following the loop.

const coll = ['one', 'two', 'three', 'four', 'stop', 'five'];

for (const item of coll) {
  if (item === 'stop') {
    break;
  }
  console.log(item);
}

The same behavior can easily be obtained without break by using the while loop. This kind of loop is semantically better suited for such a problem, since it implies an incomplete iteration:

const coll = ['one', 'two', 'three', 'four', 'stop', 'five'];

let i = 0;
while (coll[i] !== 'stop') {
  console.log(coll[i]);
  i += 1;
}

The while is ideal for situations where the number of iterations is unknown in advance, such as in the code above, when waiting for an exit condition or when searching for a prime number. When the number of iterations is known, it is preferable to use the for loop.

Continue

The continue instruction allows you to skip an iteration of the loop. Below is an example with the myCompact() function, which removes null elements from an array:

const myCompact = (coll) => {
  const result = [];

  for (const item of coll) {
    if (item === null) {
      continue;
    }

    result.push(item);
  }

  return result;
};

The code without continue is simpler:

const myCompact = (coll) => {
  const result = [];

  for (const item of coll) {
    if (item !== null) {
      result.push(item);
    }
  }

  return result;
};

Summary

break and continue are designed to make managing the traversal more flexible. In practice, you can always build code without them, and it will probably be even simpler. Avoid these constructions if possible.


Recommended materials

  1. Documentation on break
  2. Documentation on continue

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY