Values for Missing Arguments
Some parameters almost always get the same value. Instead of making every caller pass it, you can give the parameter a default value. The default is used when the caller leaves that argument out:
function greet(name, greeting = "Hello") {
console.log(`${greeting}, ${name}!`);
}
greet("Ada");
greet("Ada", "Welcome back");
Output:
Hello, Ada!
Welcome back, Ada!
The first call does not pass a greeting, so the default "Hello" is used. The second call passes "Welcome back", so that value is used instead.
Put parameters with defaults after the ones without defaults. Arguments are matched to parameters from left to right, so a default at the end is the one a caller can leave out.
JavaScript does not complain if a call passes fewer arguments than the function has parameters. A missing argument simply becomes undefined. A default value replaces it:
function greet(name, greeting = "Hello") {
console.log(`${greeting}, ${name}!`);
}
greet();
greet(undefined, "Hi");
Output:
Hello, undefined!
Hi, undefined!
greet() has no arguments at all. greeting gets its default, but name has no default, so it is undefined, and JavaScript prints that word. No error appears. The second call shows that passing undefined on purpose counts as "missing" too. So a default fills in a missing value, but it does not check that the important values are there. If a parameter is required, the function has to check it itself, for example with if (name === undefined). The Errors section shows what to do when the check fails.
Keep default values simple and obvious. A reader who sees greeting = "Hello" knows at once how the function is usually called.
In the exercise, give greeting the default value "Hello", then finish a call that passes a different greeting.