1/*A function may be defined with several parameters, or with no
2parameters at all. Even if a function is defined with parameters,
3JavaScript will not complain if the function is called without
4specifying the value of each parameter.*/
5
6function hello(name) {
7 return `Hello, ${name}!`;
8}
9
10console.log(hello());
11
12//Hello, undefined!
13
14
15/*We defined hello to have one parameter, name. When calling it,
16however, we did not provide any arguments. Regardless, the program ran
17without error.
18
19Arguments are optional when calling a function. When a function is
20called without specifying a full set of arguments, any parameters that
21are left without values will have the value undefined.*/
1/*Just as it is possible to call a function with fewer arguments than it
2has parameters, we can also call a function with more arguments than it
3has parameters. In this case, such parameters are not available as a
4named variable.
5
6This example calls hello with two arguments, even though it is defined
7with only one parameter.*/
8
9function hello(name = "World") {
10 return `Hello, ${name}!`;
11}
12
13console.log(hello("Jim", "McKelvey"));
1/*If your function will not work properly without one or more of its
2parameters defined, then you should define a default value for these
3parameters. The default value can be provided next to the parameter
4name, after =.
5
6This example modifies the hello function to use a default value for
7name. If name is not defined when hello is called, it will use the
8default value.*/
9
10function hello(name = "World") {
11 return `Hello, ${name}!`;
12}
13
14console.log(hello());
15console.log(hello("Lamar"));
16
17//Hello, World!
18//Hello, Lamar!
1/*While this may seem new, we have already seen a function that allows
2for some arguments to be omitted---the string method slice.
3
4The string method slice allows the second argument to be left off. When
5this happens, the method behaves as if the value of the second argument
6is the length of the string.*/
7
8// returns "Launch"
9"LaunchCode".slice(0, 6);
10
11// returns "Code"
12"LaunchCode".slice(6);
13
14// also returns "Code"
15"LaunchCode".slice(6, 10);