---
title: "How do for loops work in Dart?"
description: "Dart has classic for, for-in, forEach and while loops, plus collection for in list literals. See each form with examples, including loops with an index."
url: "https://bugsee.com/answers/dart/dart-for-loops-made-simple-a-quick-guide/"
---

# How do for loops work in Dart?

Use `for (var i = 0; i < n; i++)` for counting, `for (final x in items)` to walk a collection, and `list.indexed` (Dart 3) when you need both the index and the value.

```dart
final names = ['Ada', 'Linus', 'Grace'];

for (var i = 0; i < names.length; i++) {
  print('$i: ${names[i]}');
}

for (final name in names) {
  print(name);
}

for (final (i, name) in names.indexed) {   // Dart 3
  print('$i: $name');
}

names.forEach(print);                       // function form

var n = 3;
while (n > 0) { n--; }

// A for inside a collection literal
final labels = [for (final n in names) n.toUpperCase()];
```

Prefer `for-in` when you do not need the index, since it cannot go out of range. Inside a `forEach` callback you cannot use `break` or `continue`, so use a normal loop when you need them.

## Related questions

- [How do you write a switch expression in Dart?](https://bugsee.com/answers/dart/dart-switch-expression-syntax-and-examples/)
