← All lessons/Functions· Lesson 21 of 32

Reuse: build a scene with a helper

Write one reusable drawing helper and call it several times to compose a whole picture.

About 8 min

Write once, use everywhere

The real power of functions is reuse. Instead of copying the same shapes over and over, write a helper once and call it many times — each call with different inputs. Less code, fewer mistakes, and changes only need to happen in one place.

Below, a single drawTree(x) helper draws a trunk and leaves at a given x. Calling it a few times plants a whole row of trees:

One helper, called four times, builds a little forest.

Spot the repetition

Whenever you find yourself copying and pasting the same shapes with small tweaks, that's a sign to make a function.

Your turn

Make a row of trees. Define a helper drawTree(x) that draws a trunk (rect) and leaves (ellipse) at position x, then call it at least 4 times with different x values to build the scene.

Hints