Java Reference
In-Depth Information
Default Arguments
We can use the fact that
undefined
is used when arguments are not supplied to provide
default values for a function. For example, we can improve the
hello
function that we
created earlier by adding a
name
parameter so that it says "hello" to the value provided as
an argument:
function hello(name){
console.log("Hello " + name + "!");
}
This works as expected, but says "hello" to
undefined
if no argument is provided:
hello("DAZ");
<< "Hello DAZ!"
hello();
<< "Hello undefined!"
We can improve the function by checking if the
name
parameter has a value of
un-
defined
and providing a default value of "World" if so:
function hello(name){
if (name === undefined) name = "World";
console.log("Hello " + name + "!");
}
Now we can invoke the
hello
function with or without arguments:
hello();
<< "Hello World!"
hello("DAZ");
<< "Hello DAZ!"
Another way of assigning default values is to use the following line:
