Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    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?

  2. 2

    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.

Back

4/10

  1. 1. Defining Functions
  2. 2. Calling Functions
  3. 3. Parameters and Arguments
  4. 4. Default Parameter Values
  5. 5. Returning Values
  6. 6. Return Ends the Function
  7. 7. Variable Scope
  8. 8. Functions and Arrays
  9. 9. Arrow Functions
  10. 10. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.