There is also a continue
statement that
starts a new iteration of the loop. This
statement can sometimes be useful for
simplifying the code, although almost
always the problem can be solved without
it. Let's look at a practical example.
Let's say we have an array of numbers. Let's
iterate over it and the numbers that are
divisible by 2
will be squared and
output to the console, but the numbers that
are divisible by 3
will be cubed and
output to the console. Here is the solution
to the described problem:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
for (let elem of arr) {
let result;
if (elem % 2 === 0) {
result = elem * elem;
console.log(result);
} else if (elem % 3 === 0) {
result = elem * elem * elem;
console.log(result);
}
}
As you can see, the line console.log(result)
is repeated twice. Let's take it out of if
,
like this:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
for (let elem of arr) {
let result;
if (elem % 2 === 0) {
result = elem * elem;
} else if (elem % 3 === 0) {
result = elem * elem * elem;
}
console.log(result); // the output taken out of condition
}
Now our script, however, works a little differently:
it turns out that for ordinary elements that are not
processed through our if
the variable
result
will be output to the console,
which, according to our task we don't need.
Let's fix the problem by adding to our if
another condition else
, which will work for
elements that are not divisible by 2
and 3
,
and call the statement continue
there, which will
immediately transfer us to a new iteration of the loop:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
for (let elem of arr) {
let result;
if (elem % 2 == 0) {
result = elem * elem;
} else if (elem % 3 == 0) {
result = elem * elem * elem;
} else {
continue; // go to a new loop iteration
}
console.log(result); // will be executed if divisible by 2 or 3
}