Functions
Files in this demo
├─ index.html └─ script.js
A function is a named piece of code you can run whenever you want. Write it once, use it everywhere.
function greet(name) {
return "Hello, " + name + "!";
}
greet("Moonbug"); // "Hello, Moonbug!"
The parts
- Parameters ~
namein the brackets. Placeholders, filled in when the function is called. - Arguments ~
"Moonbug". The actual values you pass in. return~ hands a value back and stops the function there and then. Code after areturnnever runs.
A function without a return still works ~ it just gives you undefined. That’s fine if its job is to do something rather than work out something.
Arrow functions
const double = (n) => n * 2;
The same idea in fewer characters. With a single expression and no curly braces, the result is returned automatically. You’ll see these everywhere in modern JavaScript, especially as one-off callbacks.
Scope
Variables declared inside a function only exist inside it. Call the function again and they start fresh. This is a feature ~ it means two functions can both use a variable called count without ever interfering with each other.
Why bother
Three reasons, and they’re all the same reason really:
- 1Don’t repeat yourself. Fix a bug once instead of in six places.
- 2Name things.
randomBetween(1, 6)reads better than the maths inside it. - 3Think in smaller pieces. A big problem becomes several small ones.
If you catch yourself copy-pasting code and changing one value, that’s a function trying to be born.
Click to resume
Use the console below.