3.11 Functions
As programs grow, you'll find lots of logic used over and over. Rewriting it each time is tiring and error-prone. Functions solve this: package a piece of logic, give it a name, and "call" it whenever you need it.
The lab below has an add function. Change the arguments, call it a few times, and see the "input → output" relationship.
Loading interactive lab...
Define and call
js
// define the function
function greet(name) {
return "Hello, " + name + "!";
}
// call the function
let message = greet("Leaf");
console.log(message); // Hello, Leaf!- Define: use the
functionkeyword, name the function (greet), and list parameters in parentheses.
- Call: write the name with parentheses
greet("Leaf"), passing in actual values.
Parameters and return value
A function is like a machine: parameters are the raw materials you put in, and the return value is the product it puts out.
js
function add(a, b) { // a, b are parameters (input)
return a + b; // return hands the result back (output)
}
add(2, 3); // 5
add(10, 20); // 30- Parameters: the function's "inputs." Values passed in fill the parameters in order.
return: hands the result back to the caller and immediately ends the function.
Loading concept check...
Loading concept check...
Why use functions
- Reuse: write once, call everywhere. Change the logic in one place.
- Readability: a name (
calculateTotal) is easier to understand than a blob of code.
- Decomposition: split a big problem into small functions, each doing one thing — easier to maintain.
Remember one line: a function should do one thing and do it well.
Arrow functions: a shorter form
In modern JS you'll often see "arrow functions," a more concise syntax:
js
// regular form
function double(x) {
return x * 2;
}
// arrow-function form (equivalent)
const double = (x) => x * 2;The => is read "arrow." For simple functions it saves a lot of typing, and you'll see it constantly later with array map and filter.
Note
Parameter vs argument. The
a, b in the definition are parameters (placeholder names); the 2, 3 you pass when calling are arguments (actual values). Don't sweat the names — just grasp "placeholder vs actual."Loading practice...