Introduction to Functions
A named little machine that does one job for you
- say what a function is in simple words,
- explain inputs and an output,
- say why we split a big program into small named pieces.
1. What is a function?
A function is a group of steps that we put together, give a name, and use whenever we want. Instead of writing the same steps over and over, we write them once inside a function. Then we just say the function's name to run all of those steps at once.
Think of making toast. The steps are: put bread in the toaster, push the lever down, wait, take out the toast. That is four steps. If we put those steps in a function called makeToast, then next time we only need to say makeToast and all four steps happen. The name stands for the whole block of steps.
2. Inputs and an output
Most functions take some inputs and give back one output.
- Input = what you put in (the things the function needs to do its job).
- The steps = the work the function does with the inputs.
- Output = what comes back out when the function is done.
For example, a function called addTwoNumbers takes two inputs (say 3 and 5), adds them, and its output is 8. Change the inputs and you get a different output: give it 10 and 2, and the output is 12. Same function, same steps, but different results depending on the inputs.