CodeBlanks Logo Icon CodeBlanks

forEach

Learn side-effect loops with forEach.

The forEach method

The forEach method performs an action for each element but returns nothing. It is used for side effects; for example printing each element.

Example: ['Apple', 'Banana', 'Cherry'].forEach((f) => print(f));. This prints each fruit on a separate line. Unlike map, forEach produces no result.

forEach replaces a loop. The code becomes shorter and more readable. But because it has no return value it cannot be chained.

forEach vs map

forEach and map look similar but serve different purposes. map returns a transformed collection; forEach returns nothing.

For side effects like printing use forEach. When you need transformed data use map. The wrong choice does not break the code but hurts readability.

Example: fruits.forEach((f) => print(f)); prints each fruit. fruits.map((f) => f.length) returns a list of lengths.

Practice Print the fruits

Call forEach on the list ['Apple', 'Banana', 'Cherry']. Print each fruit with a 'Fruit: ' prefix; for example Fruit: Apple.

Starter code

main.dart
void main() {
  var fruits = ['Apple', 'Banana', 'Cherry'];
  // use .forEach to print each fruit with a 'Fruit: ' prefix
}

Sample solution

main.dart
void main() {
  var fruits = ['Apple', 'Banana', 'Cherry'];
  fruits.forEach((f) => print('Fruit: $f'));
}

Expected output

Fruit: Apple
Fruit: Banana
Fruit: Cherry

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does forEach return?

main.dart
var a = [1, 2, 3].forEach((n) => print(n));
  • A new list
  • void (returns nothing) Correct answer
  • An Iterable
  • A number

Explanation: forEach returns nothing, it is void.

2 Match the forEach parts

Term Meaning
(m) => print(m) Side effect function
.forEach(...) Call
void Return type
print(m) Print action

3 The forEach call

Question
var fruits = ['Apple', 'Banana', 'Cherry'];
fruits.____((f) => print('Fruit: $f'));
Answer
var fruits = ['Apple', 'Banana', 'Cherry'];
fruits.forEach((f) => print('Fruit: $f'));

Explanation: forEach performs an action per element.

All lessons in Intermediate