Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære break and continue | Loops in Dart
Introduction to Dart

book
break and continue

break

In Dart, break is a statement used to exit a loop. The break statement can be used in any loop, including while, for, and do-while loops.

The syntax for the break statement is as follows:

javascript
break;

When the break statement is encountered in code, it terminates the execution of the loop in which it is located. This means that any other iterations of the loop will not be executed.

Example

The break statement is often used to exit a loop if a condition meets specific requirements. For example, the following code prints all numbers from 1 to 10, but it breaks the loop if it encounters the number 5:

main.dart

main.dart

copy
void main() {
int counter = 1;

while (counter <= 10) {
if (counter == 5) {
break;
}
print(counter);
counter++;
}
}
1234567891011
void main() { int counter = 1; while (counter <= 10) { if (counter == 5) { break; } print(counter); counter++; } }

continue

Continue is a statement used to skip the current iteration of a loop. The continue statement can be used in any loop, including while, for, and do-while loops.

The syntax for the continue statement is as follows:

javascript
continue;

Example

The continue statement is often used to skip certain values or conditions

main.dart

main.dart

copy
void main() {
List<String> actions = ["go", "jump", "stop", "go", "go", "stop", "jump", "stop", "go", "go", "stop"];
for (String item in actions) {
if (item == "stop"){
continue;
}
print(item);
}
}
123456789
void main() { List<String> actions = ["go", "jump", "stop", "go", "go", "stop", "jump", "stop", "go", "go", "stop"]; for (String item in actions) { if (item == "stop"){ continue; } print(item); } }

As you can see, the continue statement allows us to control which list items will be output to the console.

question mark

Which statement stops the loop?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 4. Kapitel 6

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

We use cookies to make your experience better!
some-alt