Parameters and Arguments
Parameters are the names a function gives to the values it expects, and arguments are the values you actually pass in.
Parameters are named in the declaration; arguments are supplied at the call. Missing arguments become undefined, extra ones are ignored, and default values fill the gaps. Objects arrive by reference, so a function can change them.
EXERCISE
1Names on the Inside, Values on the Outside
A parameter is a variable that exists only inside the function and gets its value from whoever calls it.
The two words describe the same slot from two sides.
Parameter is the name, argument is the value:
function greet(name, greeting) {
// ^^^^ ^^^^^^^^ parameters
console.log(`${greeting}, ${name}`);
}
greet("Ada", "Hello");
// ^^^^^ ^^^^^^^ arguments
// Hello, Ada
Parameters are matched by position, not by name:
function describe(name, age) {
console.log(`${name} is ${age}`);
}
describe("Ada", 36); // Ada is 36
describe(36, "Ada"); // 36 is Ada <- no warning, just wrong
Too few arguments gives undefined, not an error:
function add(a, b) {
console.log(a, b);
return a + b;
}
console.log(add(2)); // 2 undefined, then NaN
console.log(add(2, 3, 9)); // 2 3, then 5 <- the extra 9 is ignored
A missing argument is undefined, not zero. That distinction is the
whole reason the first line gives NaN: 2 + undefined is not 2, because
undefined is not a number and arithmetic on it has no answer to give.
console.log(2 + undefined); // NaN
console.log(2 + 0); // 2 <- what people expect, and not what happens
And a parameter is local to the function:
function shout(word) {
word = word.toUpperCase(); // changing the parameter
return word;
}
const original = "hello";
console.log(shout(original)); // HELLO
console.log(original); // hello <- untouched
will never stop you calling a function with the wrong number of arguments, and it will never check the types either. A function called with two arguments when it wanted three does not throw, it produces undefined somewhere in the middle and fails later in a confusing place. Default values, in the next exercise, are the standard defence.
EXERCISE
2Default Values and Too Many Parameters
A default fills in for an argument that was not supplied, and once a function needs more than three, an object argument reads better.
A default is written with an equals sign in the parameter list:
function greet(name, greeting = "Hello") {
console.log(`${greeting}, ${name}`);
}
greet("Ada"); // Hello, Ada
greet("Ada", "Welcome"); // Welcome, Ada
Defaults apply only for undefined, not for other falsy values:
function repeat(text, times = 3) {
console.log(times);
}
repeat("hi"); // 3 nothing passed
repeat("hi", undefined); // 3 explicitly undefined counts as nothing
repeat("hi", 0); // 0 zero is a real value, no default
repeat("hi", null); // null null is a real value too
A default can use an earlier parameter:
function makeTag(name, closing = `</${name}>`) {
return `<${name}>${closing}`;
}
console.log(makeTag("p")); // <p></p>
When there are several optional values, pass an object:
// Hard to call correctly: what is the fourth true?
function createUser(name, email, isAdmin, isVerified, sendWelcome) { }
createUser("Ada", "a@x.com", false, true, true);
// Named at the call site, order no longer matters:
function createUser2({ name, email, isAdmin = false, sendWelcome = true }) {
console.log(name, email, isAdmin, sendWelcome);
}
createUser2({ name: "Ada", email: "a@x.com", sendWelcome: false });
// Ada a@x.com false false
Pro Tip: Two or three parameters read fine in a call. Beyond that, a reader at the call site is counting commas to work out what each value means, and every boolean argument is a small puzzle. Switching to a single object argument names each value where it is supplied, and gives you free defaults for the ones that were left out.
EXERCISE
3What a Function Can and Cannot Change
A function cannot reassign the variable you passed in, but it can change the contents of an object, and that difference matters.
This is the primitives-versus-objects rule from Unit 2, seen from inside a function.
A primitive argument is a copy, so the original is safe:
function birthday(age) {
age = age + 1;
return age;
}
let myAge = 36;
console.log(birthday(myAge)); // 37
console.log(myAge); // 36 <- unchanged
An object argument is shared, so the function can change it:
function birthdayFor(user) {
user.age = user.age + 1;
}
const ada = { name: "Ada", age: 36 };
birthdayFor(ada);
console.log(ada.age); // 37 <- the original object changed
But reassigning the parameter still does nothing outside:
function replace(user) {
user = { name: "Someone else" }; // points the LOCAL name elsewhere
}
const grace = { name: "Grace" };
replace(grace);
console.log(grace.name); // Grace <- untouched
Which is why returning a new object is usually the safer style:
// Changes the caller's object, often unexpectedly:
function addTax(order) {
order.total = order.total * 1.18;
}
// Leaves the input alone and hands back a new value:
function withTax(order) {
return { ...order, total: order.total * 1.18 };
}
const order = { id: 1, total: 100 };
const taxed = withTax(order);
console.log(order.total); // 100 untouched
console.log(taxed.total); // 118
The ...order there copies every field of the original into the new object. It is called spread, and Unit 8 covers it properly.
Pro Tip: A function that changes an object it was given is doing something the caller cannot see from the call site. Sometimes that is exactly what you want, and then the name should say so:
sortInPlace,addItemTo. When it is not, return a new value instead, and the function becomes something you can call anywhere without wondering what else it touched.
