CodeBlanks Logo Icon CodeBlanks

Default parameters

JavaScript course · Beginner · Lesson 82/133

Learn what happens with missing arguments by setting default parameter values.

Default parameters

In JavaScript you can give a parameter a default value. If the caller does not pass an argument for that parameter, the default value is used. The syntax is the parameter name followed by = and a value.

Example: function greet(name = "Guest") { console.log("Hello " + name); }. Here the default value of name is "Guest". In the call greet() no argument is given, so name takes this value and the screen shows Hello Guest.

When no argument is given

If you do not give a parameter a default and the caller passes no argument, that parameter's value becomes undefined. This is often undesirable.

When you set a default, your chosen value is used instead of undefined. So in function greet(name = "Guest"), the call greet() does not make name undefined; it makes it "Guest". The function then works safely even with a missing argument.

Exercise Greeting function

Define a function called greet. Give the name parameter a default value of "Guest". In the body, print the greeting with console.log("Hello " + name). Then call it with no arguments as greet().

Show example solution
function greet(name = "Guest") {
  console.log("Hello " + name);
}

greet();

Test yourself

  1. Which is a valid default parameter syntax?

    function greet(name)
    • function greet(name := "Guest")
    • function greet(name = "Guest")
    • function greet(name -> "Guest")
    • function greet(name: "Guest")
    Show answer

    function greet(name = "Guest") — Correct. The = sign assigns the default value.

  2. Add the default value

    function greet(
      ____
    ) {
      console.log("Merhaba " + name);
    }
    greet();
    Show answer
    function greet(
      name = "Misafir"
    ) {
      console.log("Merhaba " + name);
    }
    greet();
  3. Match the terms

    name
    Parameter
    "Alex"
    Argument
    undefined
    When no argument is given
    "Guest"
    Default value

All lessons in Beginner