Parameters and Return
Inputs and outputs.
A function becomes much more useful when you can give it information, and get a result back. The information going in is called a parameter. The result coming out is the return value.

- Give it information
- Get a result back
- Parameters and return
In and out
Name, inside the brackets, is a parameter. When we call greet with Ana, name holds Ana. Area takes two parameters, and return sends the answer back to whoever called it. We can store that answer, or use it straight away. Run it.
function greet(name) {
console.log(`Hello, ${name}!`);
}
function area(width, height) {
return width * height;
}
greet("Ana");
const room = area(4, 5);
console.log("Room:", room, "square metres");
console.log("Garden:", area(10, 3));Hello, Ana! Room: 20 square metres Garden: 30
Return ends the function
As soon as return runs, the function stops, and hands back its value. Any code after it is skipped. A function with no return gives back undefined. Printing inside a function, and returning a value, are different things. Return is how one function passes results to another.
| key | value |
|---|---|
| Parameter | an input name |
| Argument | the value you pass |
| return | sends a result back |
| No return | gives undefined |
Returning early
A function can have more than one return. Here, the first return handles bad input, and leaves straight away. That's called an early return, or a guard. The main calculation only runs when the input is good, and it isn't buried inside an if. Run it.
function average(numbers) {
if (numbers.length === 0) {
return 0;
}
let total = 0;
for (const n of numbers) total += n;
return total / numbers.length;
}
console.log(average([4, 8, 6]));
console.log(average([]));6 0
Summary
Parameters bring values into a function, and return sends a result out. Next, default values for parameters.
Key takeaways- function f(a, b)
- return a result
- Store or use it