Answers for "10.4.3. Arguments Are Optional // Functions"

0

10.4.3. Arguments Are Optional // Functions

/*A function may be defined with several parameters, or with no 
parameters at all. Even if a function is defined with parameters, 
JavaScript will not complain if the function is called without 
specifying the value of each parameter.*/

function hello(name) {
   return `Hello, ${name}!`;
}

console.log(hello());

//Hello, undefined!


/*We defined hello to have one parameter, name. When calling it, 
however, we did not provide any arguments. Regardless, the program ran 
without error.

Arguments are optional when calling a function. When a function is 
called without specifying a full set of arguments, any parameters that
are left without values will have the value undefined.*/
Posted by: Guest on June-28-2021
0

10.4.3. Arguments Are Optional // Functions

/*Just as it is possible to call a function with fewer arguments than it 
has parameters, we can also call a function with more arguments than it 
has parameters. In this case, such parameters are not available as a 
named variable.

This example calls hello with two arguments, even though it is defined 
with only one parameter.*/

function hello(name = "World") {
   return `Hello, ${name}!`;
}

console.log(hello("Jim", "McKelvey"));
Posted by: Guest on June-28-2021
0

10.4.3. Arguments Are Optional // Functions

/*If your function will not work properly without one or more of its 
parameters defined, then you should define a default value for these 
parameters. The default value can be provided next to the parameter 
name, after =.

This example modifies the hello function to use a default value for 
name. If name is not defined when hello is called, it will use the 
default value.*/

function hello(name = "World") {
   return `Hello, ${name}!`;
}

console.log(hello());
console.log(hello("Lamar"));

//Hello, World!
//Hello, Lamar!
Posted by: Guest on June-28-2021
0

10.4.3. Arguments Are Optional // Functions

/*While this may seem new, we have already seen a function that allows 
for some arguments to be omitted---the string method slice.

The string method slice allows the second argument to be left off. When 
this happens, the method behaves as if the value of the second argument 
is the length of the string.*/

// returns "Launch"
"LaunchCode".slice(0, 6);

// returns "Code"
"LaunchCode".slice(6);

// also returns "Code"
"LaunchCode".slice(6, 10);
Posted by: Guest on June-28-2021

Code answers related to "10.4.3. Arguments Are Optional // Functions"

Code answers related to "Javascript"

Browse Popular Code Answers by Language