Default Parameter Values

What happens when you call a function with fewer arguments than it has parameters? Let's try it:

function orderCoffee(type, size) {
    console.log(`${type}, size: ${size}`);
}

orderCoffee("Latte", "large");
orderCoffee("Espresso");

This prints:

Latte, size: large
Espresso, size: undefined

There's no error. The parameter size just didn't get a value, so it is undefined, the special value that means “nothing is here”, which you know from arrays.

Often, there is a value that fits most of the time, and we only want to pass a different one now and then. Most people order a medium coffee, for example. For such cases, a parameter can have a default value: after the name of the parameter, write = and the value:

function orderCoffee(type, size = "medium") {
    console.log(`${type}, size: ${size}`);
}

orderCoffee("Latte", "large");
orderCoffee("Espresso");

This prints:

Latte, size: large
Espresso, size: medium

When the call passes an argument for size, the function uses it. When it doesn't, the function uses the default value "medium".

Because arguments go into parameters in order, parameters with default values go at the end. Then you can leave out the last arguments, and the ones you pass still go into the right parameters.

Instructions

Our shop shows most prices in euros. At the end of the program, add the call printPrice(25);, without a currency. What does the last line say?

Give the parameter currency the default value "EUR". The last line then says Price: 25 EUR, and the other two calls still print their own currencies.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

4/10

Next