After this lesson you can design a function's inputs and outputs: add several parameters, give them sensible defaults, and return exactly the result the caller needs.
Parameters and arguments
People mix these two words up, and it does not matter much in conversation. The precise meaning is:
- A parameter is a name listed in the function definition.
- An argument is the real value you supply when you call the function.
function add(a, b) { // a and b are parameters
return a + b;
}
console.log(add(2, 3)); // 2 and 3 are arguments. Logs 5Arguments are matched to parameters by position: the first argument goes to the first parameter, and so on.
JavaScript is relaxed about how many arguments you pass. Extra arguments are ignored. Missing ones become undefined:
function add(a, b) {
return a + b;
}
console.log(add(1)); // NaN, because 1 + undefined is NaN
console.log(add(1, 2, 3)); // 3, the third argument is ignoredThat NaN is the usual sign that you forgot an argument.
Default values
You can give a parameter a fallback with =:
function greet(name = "friend") {
return "Hello, " + name + "!";
}
console.log(greet("Asha")); // Hello, Asha!
console.log(greet()); // Hello, friend!The default is used only when the argument is missing or exactly undefined. Other values, including 0, "", false and null, are kept as they are:
function show(count = 10) {
return count;
}
console.log(show()); // 10
console.log(show(undefined)); // 10
console.log(show(0)); // 0
console.log(show(null)); // nullDefaults can use earlier parameters and can be any expression:
function box(width, height = width) {
return width + " x " + height;
}
console.log(box(5)); // 5 x 5
console.log(box(5, 2)); // 5 x 2Put parameters with defaults after the required ones. That keeps calls tidy, because you can leave off the optional ones at the end.
Named options with an object
When a function takes many values, call sites like createButton("Save", true, false, 12) are impossible to read. A common fix is to accept one object and pick values out of it, with defaults:
function createButton({ label, primary = false, size = 14 }) {
return label + " (primary: " + primary + ", size: " + size + ")";
}
console.log(createButton({ label: "Save", primary: true }));
// Save (primary: true, size: 14)
console.log(createButton({ label: "Cancel" }));
// Cancel (primary: false, size: 14)The curly braces in the parameter list are destructuring, which a later lesson covers fully. For now, read it as "take these named properties from the object I was given". The order no longer matters and each call explains itself.
Return values
A function returns one value, using return. After a return, the function stops. You can use this to leave early:
function divide(a, b) {
if (b === 0) {
return "Cannot divide by zero";
}
return a / b;
}
console.log(divide(10, 2)); // 5
console.log(divide(1, 0)); // Cannot divide by zeroThis "return early" style avoids deep nesting. Check for the bad case first, leave, and keep the main logic flat.
Returning more than one thing
You cannot write return a, b to get two values. Instead, bundle them:
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
function show(text) {
out.textContent += text + "\n";
}
function minMax(numbers) {
return { min: Math.min(...numbers), max: Math.max(...numbers) };
}
const result = minMax([4, 9, 2, 7]);
show("min: " + result.min);
show("max: " + result.max);
function splitName(fullName) {
return fullName.split(" ");
}
const [first, last] = splitName("Asha Rao");
show(first + " / " + last);
</script>An object is best when the pieces have names. An array is fine for short, ordered pairs. The [first, last] form on the last lines is array destructuring, covered later in this course.
One trap: a return followed by a line break returns undefined, because JavaScript inserts a semicolon. Start the returned value on the same line as return:
function broken() {
return
{ ok: true };
}
console.log(broken()); // undefinedValues are copied, objects are shared
When you pass a number, string or boolean, the function gets its own copy. Changing the parameter does not affect the caller's variable. Objects and arrays behave differently: the function receives a reference to the same object.
function addOne(n) {
n = n + 1;
return n;
}
let count = 5;
addOne(count);
console.log(count); // 5, unchanged
function addItem(list) {
list.push("new");
}
const items = ["a"];
addItem(items);
console.log(items); // [ 'a', 'new' ]Changing a caller's data from inside a function is called a side effect. It is sometimes what you want, but surprising side effects are a classic source of bugs. Prefer returning a new value when you can.
Validating inputs
Because JavaScript accepts any argument, a function that must be strict has to check for itself. A small guard at the top keeps bad data out:
function percent(part, total) {
if (typeof part !== "number" || typeof total !== "number" || total === 0) {
return null;
}
return Math.round((part / total) * 100);
}
console.log(percent(1, 4)); // 25
console.log(percent("1", 4)); // null
console.log(percent(1, 0)); // nullDecide what your function returns for invalid input, such as null or an error message, and keep that choice consistent.
Common mistakes
Expecting the right number of arguments. JavaScript will not warn you. A missing argument quietly becomes undefined, and you find out later as NaN or an odd string.
Assuming defaults cover null or 0. They only cover undefined. If null can arrive, handle it yourself.
Reassigning a parameter and expecting the caller to change. For numbers and strings, it will not. Return the new value instead.
Mutating an array argument by accident. Methods such as push, sort and splice change the original. Copy first if you need to keep it.
Putting the return value on the next line. return then newline returns undefined.
Forgetting to return at all. If the result is undefined, check whether you printed instead of returning.
Exercise
Write formatPrice(amount, currency = "USD", decimals = 2) that returns a string like "USD 12.50". Call it with only an amount, with a currency, and with all three. Then write stats(numbers) that returns an object with total, average and count, and print each field. Hint: toFixed is a number method that formats decimals.
Next: Arrow functions, a shorter way to write functions. If you want to revisit the basics, go back to Functions.
Key points
- Parameters are the names in the function definition; arguments are the actual values you pass in a call.
- A missing argument becomes undefined unless the parameter has a default value.
- Default values are written with an equals sign and only apply when the argument is missing or undefined.
- A function returns one value; to return several, wrap them in an object or an array.
- Primitive arguments are copied, but objects and arrays are passed by reference, so changing them inside a function changes the original.