JavaScript course menu
JavaScript Function Parameters: Default Values, Rest Parameters and Spread Arguments
Learn JavaScript function parameters in depth: default parameter values, rest parameters (...args) for any number of arguments, spreading arrays into calls, destructured object parameters for named options, and how arguments are passed (values and references).
On this page
JavaScript functions are flexible about their inputs. This lesson shows how to give parameters defaults, accept any number of arguments, and pass named options.
Default parameter values#
A default is used when the argument is missing or undefined:
function greet(name = "friend", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
console.log(greet());
console.log(greet("Asha"));
console.log(greet("Asha", "Namaste"));
console.log(greet(undefined, "Hi"));Hello, friend!
Hello, Asha!
Namaste, Asha!
Hi, friend!Passing null does not trigger the default, because null is a deliberate value:
function greet(name = "friend") {
return `Hello, ${name}!`;
}
console.log(greet(null));Hello, null!Defaults can use earlier parameters: function area(width, height = width) { ... } makes a square when only one side is given.
Rest parameters#
...name as the last parameter collects all remaining arguments into an array:
function sum(...numbers) {
let total = 0;
for (const n of numbers) total += n;
return total;
}
console.log(sum());
console.log(sum(5));
console.log(sum(1, 2, 3, 4));0
5
10You can combine normal parameters with a rest parameter:
function logWithLabel(label, ...values) {
console.log(`[${label}]`, values.join(", "));
}
logWithLabel("scores", 92, 85, 78);[scores] 92, 85, 78(Older code uses the special arguments object for this. Rest parameters are clearer and give a real array.)
Spread in calls#
The same ... syntax used in a call does the opposite: it spreads an array into separate arguments:
const marks = [72, 91, 64, 88];
console.log(Math.max(...marks));
console.log(Math.min(...marks));
function fullName(first, last) {
return `${first} ${last}`;
}
const parts = ["Asha", "Rao"];
console.log(fullName(...parts));91
64
Asha RaoMath.max(marks) without the spread would return NaN, because it would receive one array instead of four numbers.
Named options with an object#
Functions with many parameters are hard to call correctly: what does createUser("Asha", true, false, 30) mean? Passing a single options object, and destructuring it in the parameter list, gives every argument a name:
function createUser({ name, isAdmin = false, age, sendWelcome = true }) {
return `${name} (age ${age}) admin=${isAdmin} welcome=${sendWelcome}`;
}
console.log(createUser({ name: "Asha", age: 30 }));
console.log(createUser({ age: 25, name: "Ravi", isAdmin: true, sendWelcome: false }));Asha (age 30) admin=false welcome=true
Ravi (age 25) admin=true welcome=falseThe order no longer matters, each value is labelled, and defaults work per option. Destructuring is explained in Destructuring and Spread.
How arguments are passed#
JavaScript always passes arguments by value, but for objects and arrays, the value is a reference to the same object. So a function can change an object's contents, but reassigning the parameter does not affect the caller:
function addItem(cart) {
cart.push("pen"); // changes the caller's array
}
function replaceCart(cart) {
cart = ["new cart"]; // only changes the local parameter
}
const myCart = ["book"];
addItem(myCart);
replaceCart(myCart);
console.log(myCart);[ 'book', 'pen' ]To avoid surprising callers, many functions return a new array or object instead of changing the one they were given: return [...cart, "pen"];.
Practice#
Practice exercise
Write formatPrice(amount, { currency = "₹", decimals = 2 } = {}) that returns the amount formatted with a currency symbol. Make the whole options object optional (that is what = {} does). Test it with 499, 499 with decimals: 0, and 12.5 with currency: "$".
Show solution
function formatPrice(amount, { currency = "₹", decimals = 2 } = {}) {
return `${currency}${amount.toFixed(decimals)}`;
}
console.log(formatPrice(499));
console.log(formatPrice(499, { decimals: 0 }));
console.log(formatPrice(12.5, { currency: "$" }));₹499.00
₹499
$12.50Without = {}, calling formatPrice(499) would fail, because JavaScript cannot destructure undefined.
Key takeaway#
Finished this lesson?