Default Parameter Values & Using Rest

Open the project folder

In our starter files, open the index.html page from this lessons folder:

03.Functions > 07.Default-parameter-values-and-using-rest

Function parameters

We will now be focusing on function parameters, and a few useful tricks when using them which were made available with the introduction of ES2015. Remember a parameter is the placeholder for the value we are going to be passing to the function, kind of like a variable.

First we will cover default parameter values. And to see this we can create a new function which takes in a currency amount, the currency symbol, then returns a string to display the price to the user:

function formatMoney(amount, currency) {
  return `${currency} ${amount}`;
}
const price = formatMoney(100, '$');
console.log(price);

Which gives us the value of $ 100. We can also go one further by changing the price to be 2 decimal places, using a JavaScript number method called toFixed:

function formatMoney(amount, currency) {
  return `${currency} ${amount.toFixed(2)}`;
}
const price = formatMoney(100, '$');
console.log(price);

This will now output $ 100.00.

Default parameters

If we had a site which only had one currency, and we always planned on using this, we could pass in a default parameter value such as $:

function formatMoney(amount, currency = '$') {
  return `${currency} ${amount.toFixed(2)}`;
}

Now we do not have to pass in a value for the currency when we call the function. Or if we did, it would override this default:

const price = formatMoney(100, '£');

Using variables as default parameters

This also works with variables too:

const currencySymbol = '$';

function formatMoney(amount, currency = currencySymbol) {
  return `${currency} ${amount.toFixed(2)}`;
}

We could maybe use this to keep one central value which we use throughout our site.

Rest parameters

Next, we have the rest parameter. This will give us an easy way to deal with a function having lots of parameters. Let’s imaging we had a function to calculate an average age from lots of different users ages:

function averageAge() {
}
averageAge(45, 32, 99, 12, 97, 15, 66);

Rather than the function having lots of different variable names for each parameter, it would be useful to convert them to one value which we can loop over, such as an array.   Yes, something like this may be already stored in an array, but for other uses there may be times when these arguments will be coming from different locations, or not grouped together, so we must deal with it ourselves.

To handle this, we have the rest parameter:

function averageAge(...ages) {

This is like a variable with the 3 dots before it. We can now use this name of ages in our function as an array:

function averageAge(...ages) {
  console.log(ages); // [45, 32, 99, 12, 97, 15, 66]
}
averageAge(45, 32, 99, 12, 97, 15, 66);

Going back to our functions purpose, which is to return the average age, for this we can use an array method we have already looked at called reduce:

function averageAge(...ages) {
  // 1. get total
  const total = ages.reduce((total, current) => current + total);
  // 2. divide by number of items in the array
  return total / ages.length;
}

const average = averageAge(45, 32, 99, 12, 97, 15, 66);
console.log(average);

The rest parameter does not need to collect all the values either, if we wanted to store the first value independently, we could do this:

function averageAge(first, ...ages) {

The first value is now stored in the first variable, and, as the name suggests, ages will collect the rest of the values. Therefore, the rest parameter must be last.

These 3 dots may look familiar from earlier when we looked at destructuring arrays:

let posts = [
  { title: "How to learn Javascript", body: "bla bla bla" },
  { title: "How to be a ninja", body: "bla bla bla" },
  { title: "How to be a ninja part 2", body: "bla bla bla" },
];
const [post1, ...others] = posts;

This example is what we looked at earlier and is an example of spread. Rest and spread are similar, and both have the 3 dots.

Spread means we can take something we can loop over, such as this array of posts, and we can pull out values and spread them into something else. For example, they can be spread into a new object or array to copy over the values.

Making is useful for things like duplicating arrays, or just generally copying values to a new location.