Functions: named mini-programs — Computing, 7–10 years
Learn how a program can give a useful group of steps a name and use it again when needed. Computing, 7–10 years.
One name, many steps
A function is a named set of instructions that performs one useful job. Instead of writing the same steps every time, a program can call the function by its name. For example, “drawSquare” might draw four equal sides whenever the program asks for it.
Why give steps a name?
The problem is repetition: a large program may need the same useful action in ten different places. Copying it ten times makes the program longer and gives ten places where a change could be missed. Functions came from the need to organise growing programs into clear, reusable pieces that people could manage.
A function for a square
We make a function called “drawSquare” with four steps: move 40 centimetres, turn right 90 degrees, and repeat that pair four times. The program stores these steps under the name “drawSquare”. Later, calling “drawSquare” at positions (1,1) and (5,3) draws two squares without rewriting the instructions.
The tempting mistake
A reasonable mistake is to think that naming steps makes them happen immediately. A function is usually only a recipe waiting to be called; it does nothing at the moment it is created. If “drawSquare” is defined but never called, no square appears. The name organises the work, but the call starts it.
Where functions are used
Functions are behind familiar actions such as “play a sound”, “send a message” or “show the next level”. A weather app can use one function to turn a temperature into a coloured display in many places. Changing that function can improve every place that calls it, which is why programmers name jobs carefully.
Keep exploring
Other languages
Loading MyLeoNes™…