From Zero to Deploy · Module 2 · Lesson 2.2
2.2 Functions, the recipes of code
What a function is, how to pass data into it, what return does, and why the AI splits everything into functions.
A function is a recipe
A function is a named piece of code you write once and use as many times as you want. Think of a recipe:
- Ingredients: the data you pass in (the parameters).
- Method: the code inside the braces
{ }. - The finished dish: what it gives back with
return.
Run the example below. What shows up in the console is what the code prints with console.log.
Challenges: change 'Ana' to your name. Then add a third line, console.log(greet(...)), with another name. You wrote the greeting once and used it three times.
Why use functions
Imagine working out how long it takes to walk to each cafe in a list. Without a function, you’d repeat the same calculation everywhere. With a function, the calculation lives in one place, with a name that explains what it does:
Challenges:
- Add a line for a cafe 1.5 km away.
- Now the person goes by bike, at 15 km/h. Instead of copying the function, give it a second parameter:
function minutesTo(km, speed), and replace the5withspeed. Test it withminutesTo(0.96, 15).
That’s what you just did: turned a specific function into a more useful one, just by replacing a fixed number with a parameter.
return: giving back isn’t showing
The most common beginner mistake: the function does the calculation but doesn’t give it back. Without return, the function ends and the result is lost. Whoever called it gets undefined (something like “there’s nothing here”).
console.log only shows a value in the console, so you can see it. return hands the value back to whoever called the function, so the code can keep using it.
Now it’s your turn. Write the code in the editor and click Run tests: the tests check each part and tell you what’s missing.
Three ways to write the same function
When the AI writes code, you’ll see functions written in different ways. They all do the same thing:
The last one, with =>, is called an arrow function. It’s short, and the AI loves it. When it’s a single line, the return is implied: (n) => n * 2 returns n * 2.
Where you’ll see this in the course
- In the 3D game, the function
alturaEm(x, z)takes a point on the map and returns the ground height there. The whole terrain and the collision check use that same function. - In the map app, a function takes two positions and returns the distance between them, to sort the cafes from nearest to farthest.
- In the “Hello, world!” button, the code that runs on every click is a function. You’ll see that in the lesson on events.
Mark it complete to track your progress.