Functions
9 min · JavaScript
Package code under a name so you can reuse it.
Enemy 1 of 5
This code defines a function named double that returns its input times 2, then calls it with 5 and prints the result. Press Run to see 10.
Why this works
A function is a named, reusable block of code: write the logic once, then run it as many times as you need just by calling its name. This is how programmers avoid repeating themselves: wrap a task in a function instead of copy-pasting the same lines everywhere they're needed.
Define one with the function keyword, a name, parameters inside ( ), and the body inside { }. Defining a function doesn't run it. JavaScript just remembers the recipe. It only actually executes when you call it by name followed by parentheses, like double(5) below.
Use return to hand a value back to whoever called the function, so that result can be stored, printed, or passed into more code. A function that never hits a return statement automatically hands back undefined instead, which is worth remembering if you ever forget the return and wonder why your value came back empty.