Sub topic 1
Parameters and Arguments
Prerequisites
This chapter assumes you know basic JavaScript syntax (let, const), how to declare and call functions, how to work with arrays and objects, and how template literals work.
Parameters Versus Arguments
A parameter is a name in a function's declaration. An argument is the value you pass in when you call the function. When the call runs, JavaScript binds the arguments to the parameters by position: the first argument goes to the first parameter, and so on.
Missing and Extra Arguments
JavaScript does not check how many arguments a call passes. A parameter with no matching argument is undefined. Any extra arguments are ignored, and no error is thrown.
function describe(a, b) {
return `a=${a}, b=${b}`;
}
console.log(describe(1)); // "a=1, b=undefined"
console.log(describe(1, 2, 3)); // "a=1, b=2"A common mistake is to assume that a missing argument causes an error. The call runs anyway, and the undefined value often causes a failure later in the code, far from the call that caused it.
Default Parameter Values
A default value is used whenever its parameter would otherwise be undefined. Defaults apply only to undefined. An explicit null counts as a real value and is passed through unchanged.
function greet(name = "guest", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
console.log(greet()); // "Hello, guest!"
console.log(greet(undefined, "Hi")); // "Hi, guest!"
console.log(greet(null)); // "Hello, null!"Defaults Are Evaluated on Every Call
The default expression runs again on each call that needs it. So a default [] creates a new array every time, and calls never share it.
function append(item, list = []) {
list.push(item);
return list;
}
console.log(append(1)); // [1]
console.log(append(2)); // [2]Using Earlier Parameters in Defaults
A default can refer to parameters declared to its left. It cannot refer to parameters on its right, because those have not been initialized yet.
function area(width, height = width) {
return width * height;
}
console.log(area(4)); // 16
console.log(area(4, 2)); // 8Exercise
Given function f(a, b = a * 2) { return [a, b]; }, what do f(3), f(3, null), and f(3, undefined) return?
Show answer
[3, 6], [3, null], and [3, 6]. The default replaces only undefined. null is passed through as given.
Exercise
Why does calling append(2) after append(1) return [2] and not [1, 2]?
Show answer
The default [] is evaluated on every call that omits list, so each call gets a new empty array.