The break
statement allows you to
terminate the loop early. Let's see when
this might come in handy. Let's say we have
a loop that prints the elements of an
array to the console:
let arr = [1, 2, 3, 4, 5];
for (let elem of arr) {
console.log(elem);
}
Suppose we are faced with the task to determine
whether the array contains the number 3
.
If there is, we will display the word
'contains'
in the console
(and if not, we will do nothing).
Let's solve our task:
let arr = [1, 2, 3, 4, 5];
for (let elem of arr) {
if (elem === 3) {
console.log('contains');
}
}
The task is solved, however, there is a problem:
after the number 3
has already been found,
the array still keeps iterating over without sense,
wasting valuable processor resources and
slowing down our script.
It would be more optimal to terminate the work
of our loop immediately after finding the number.
This can be done using the special statement
break
, which allows you to terminate the
loop ahead of schedule.
So, let's terminate the loop as soon
as we meet the number 3
:
let arr = [1, 2, 3, 4, 5];
for (let elem of arr) {
if (elem == 3) {
console.log('contains');
break; // get out of the loop
}
}
The statement break
can terminate
any loop: the usual for
,
while
, and so on.
Given an array of numbers. Run a loop that
prints the elements of this array to the
console one by one until an element with
the value 0
is encountered. After
that, the loop should finish work.
Given an array of numbers. Find the sum of the elements from the beginning of the array to the first negative number.
Given an array of numbers. Find the position
of the first number 3
in this array
(we assume that this number must be in the array).
Determine how many integers, starting with
the number 1
, must be added to make
the sum greater than 100
.