layman/terms
How code gets made

Function

funk · shun

In shortA function is a named set of steps in a program that does one job. Write it once, then use it whenever that job needs doing.

You don't rewrite a recipe each time you bake. You pull out the same card. Programmers do the same with functions.

In a family kitchen there’s often one recipe card for the cookies everyone loves. It’s floury and bent at the corners. Every time someone wants cookies, they don’t invent the recipe again. They pull out the same card and follow it.

A function is that recipe card inside a program. It’s a named set of steps that does one job. The program can “call” it whenever it needs that job done, as many times as it likes.

Ingredients in, result out

A recipe takes ingredients and gives you cookies. A function takes some information, does its steps and usually hands back a result:

Why programmers love them

Write the steps once and use them everywhere. If there’s a mistake, you fix it in one place and every use is fixed. And a long program becomes a set of small, named jobs that are much easier to read.

Where the comparison breaks down

A recipe card is followed by a person who can improvise. A function is followed exactly, every time. And functions can use other functions, like a cake recipe that says “make the icing card first”.

How the words fit together

Functions work with variables: the information going in and coming out. They’re the basic blocks of code. An algorithm is often written as one or more functions, and refactoring often means splitting messy code into clearer functions.

Pro tip

A good function does one job and its name says what that job is, like sendReceipt. If you can't name it simply, it's probably doing too much.

When you'll hear it

“Just call that function.” Use the steps we already wrote instead of writing them again.

“What does it return?” What does the function hand back when it's finished?

“Let's pull that into a function.” Those steps are repeated in a few places, so let's write them once and reuse them.

Say it in a meeting

“Are we building this once in a way we can reuse, or copying it into every place it's needed?”