JavaScript Loop Control Statements Tutorial
#JavaScript Loop Control Statements Turial
Learn how to control the flow of loops in JavaScript using break, continue, and labels.
Loop control statements in JavaScript help manage the execution flow within loops. These tools are essential for writing efficient and readable code.
Loop control statements allow you to:
Exit a loop early
Skip specific iterations
Control nested loops using labels
JavaScript provides three main loop control tools:
break
continue
label
(used with break
and continue
)
break
Statement
The break
statement exits the loop immediately, regardless of the condition.
for (let i = 0; i < 10; i++) {
if (i === 5) break;
console.log(i);
}
// Output: 0 1 2 3 4
continue
Statement
The continue
statement skips the current iteration and proceeds to the next one.
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
console.log(i);
}
// Output: 0 1 3 4
break
and continue
Labels allow you to control nested loops more precisely.
outerLoop:
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === j) break outerLoop;
console.log(`i: ${i}, j: ${j}`);
}
}
Use break
to terminate a loop early when a condition is met.
Use continue
to skip unnecessary iterations.
Use labels
when dealing with nested loops that need complex control.
Avoid overusing labels; they can make code harder to follow.
Prefer simpler loop logic when possible.
Always comment your code when using nested control statements.
Loop control statements like break
, continue
, and labels provide essential tools for controlling flow in JavaScript loops. Mastering these helps you write efficient, bug-free code.