Skip to Content
Course content

30: Default and Rest Parameters

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're ordering a custom pizza over the phone. The shop has a standard process. If you don't specify a crust, they automatically give you "Hand-Tossed." If you don't specify a size, they assume "Large." Those are the defaults; they keep the order moving even when you're undecided. But then there are the toppings. You might want just pepperoni, or you might want a chaotic mix of olives, mushrooms, pineapple, and ham. The shop doesn't have a separate slot for "Topping 1," "Topping 2," and "Topping 3"—they just have a general list where they jot down every extra thing you ask for until you're done.

In JavaScript, Default Parameters are that "Hand-Tossed" crust. They let you assign a fallback value to a function argument if no value (or undefined) is passed. Rest Parameters are that toppings list; they allow a function to capture an indefinite number of arguments into a single, neat array.

Handling the "I forgot to tell you" scenario

Before we had default parameters, I used to spend half my time writing if (!role) { role = 'Guest'; } at the top of every function. It was noisy and tedious. Now, we can bake that logic directly into the function signature.

function createMemberProfile(username, role = 'Guest', status = 'Pending') {
  return {
    username: username,
    role: role,
    status: status
  };
}

// I provide everything
console.log(createMemberProfile('dev_dan', 'Admin', 'Active')); 
// { username: 'dev_dan', role: 'Admin', status: 'Active' }

// I only provide the username; the others fall back to defaults
console.log(createMemberProfile('coding_cat')); 
// { username: 'coding_cat', role: 'Guest', status: 'Pending' }

One thing to keep in mind: default parameters only kick in if the argument is undefined. If you explicitly pass null, JavaScript treats that as an intentional value, and the default won't trigger. It's a small detail, but it's the kind of thing that'll trip you up in a production bug if you aren't looking for it.

Gathering the leftovers

Sometimes you don't know how many arguments a user will throw at your function. Maybe it's a list of prices to sum up, or a series of tags for a blog post. This is where the rest parameter—the ... syntax—comes in. It tells JavaScript: "Take everything else that was passed in and put it into an array."

function buildShoppingCart(couponCode, ...items) {
  console.log(`Applying coupon: ${couponCode}`);
  console.log(`Items to process:`, items); 
  // 'items' is now a real array, so we can use .map, .filter, etc.
  return items.length;
}

buildShoppingCart('SAVE20', 'Laptop', 'Mouse', 'Keyboard', 'HDMI Cable');
// Applying coupon: SAVE20
// Items to process: ['Laptop', 'Mouse', 'Keyboard', 'HDMI Cable']

I love rest parameters because they replace the old, confusing arguments object. Rest parameters are actual Arrays, meaning you get all the modern array methods right out of the box without having to "convert" them first.

Combining the two for maximum flexibility

You can use both in the same function, but there's a strict rule: the rest parameter must be the last one in the list. You can't gather the "leftovers" and then try to define another specific parameter after them. That would be like the pizza shop taking your list of toppings and then asking, "Oh, and what size did you want?" after they've already started tossing the dough.

function registerEvent(eventName, guestCount = 1, ...guestNames) {
  console.log(`Event: ${eventName}`);
  console.log(`Expected guests: ${guestCount}`);
  console.log(`Guest list: ${guestNames.join(', ')}`);
}

// Here, 'JavaScript Conf' is eventName, 
// 50 is guestCount, 
// and everything else goes into guestNames.
registerEvent('JavaScript Conf', 50, 'Alice', 'Bob', 'Charlie');



📋 Practical Task

Build a Dynamic Expense Report Generator

You need to create a function called generateExpenseReport that helps an employee track their spending. The function should meet the following requirements:

  • The first parameter should be employeeName (required).
  • The second parameter should be currency, which should default to 'USD' if not provided.
  • The final parameter should be a rest parameter called expenses that collects any number of numeric values.

Inside the function, calculate the total of all expenses using a loop or an array method (like reduce). The function should return a string in this format: "Employee [name] spent a total of [total] [currency]."

Test your code with these two scenarios:

  1. Pass only the name and a list of numbers (e.g., 'Sarah', 10, 25, 100). It should use the default currency.
  2. Pass the name, a different currency, and a list of numbers (e.g., 'Mike', 'EUR', 5, 12, 40).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.