A name for a group of steps
Two bus stops need the same three lines.
- Two stops. Three lines print at each one.
- The three lines repeat. Box them together.
- Named
stopRoutine, then called at each stop. - The same eight lines still print.
Switch on the function below. Then read what prints.
Loading lab…
The rule
A function is a named group of lines. Its definition is the lines and their name.
`` function stopRoutine() { print("Bell: two taps"); print("Doors open"); print("Doors close"); } ``
A call is stopRoutine();. It runs the body, the lines inside the curly brackets.
A function gives a group of lines one name. Writing the definition runs nothing. It runs at each call, and what gets printed does not change.
In this editor, a definition may sit below its call.
| Lines written | Lines printed | |
|---|---|---|
| Repeated | 8 | 8 |
| Named | 9 | 8 |
The definition takes 5 lines. Two calls take 2 more. That is 7 lines, against 6 copied lines. So at two stops, naming costs 1 more line. The name saves writing when a group repeats many times. Each extra stop adds 1 call line, not 3 copied lines.