Default Parameter Values
Sometimes it is useful to set a default value for a parameter. For example, when the parameter value is often repeated.
Default parameter values allow us to call a function without having to specify all parameter values. If a parameter value with a default value is not specified, its default value is used. We specify the default value of a parameter when defining the function using the =
operator. For example:
function greet(name="world") {
console.log("Hello, " + name);
}
This function has one parameter name
with a default value of "world"
. When we call the function without the parameter value:
greet(); // Prints: Hello, world
The function uses the default value and prints Hello, world
.
When we call the function with the parameter value:
greet("Carl"); // Prints: Hello, Carl
The function uses the specified value and prints Hello, Carl
.
Instructions
Set the default value of the parameter name
in the function welcome
to "visitor"
.
Start programming for free
5/7