Named Parameters is unclear to me
stared opened this issue · comments
Piotr Migdał commented
Named Parameters ins unclear to me.
In particular:
- do I refer to them the same way as to "not-named" parameters?
- how do I call this function? (
func(a=1)
orfunc({a= 1})
) - how do I combine named and not-named parameters?
David Leonard commented
In order:
You refer to them the same way as parameters that are not named, which is essentially a function call:
function addNumbers(a, b) {
return a + b;
}
addNumbers(2, 3);
function someName(a=1)
is a function whose default value for a
is 1. If you call the function like so:
function someName(a=1) {
return a + 100;
}
someName( ); // Calling the function with no parameters will return 101, variable (a) takes the value of 1.
someName(3); // Calling the function with (A) returns 103, variable (a) takes the value of 3.
As for using the destructuring operation on a function func({a = 1})
:
function addNumbers({a = 0, b = 0}) {
// Through destructuring, we can access variables a and b here
return a + b;
}
addNumbers({a: 10, b:20}); // Call the function with the needed parameters
Lastly, we can combine named and not-named parameters like this:
function addNumbers({a = 0, b = 0}, c) {
// Through destructuring, we can access variables a and b here
return a + b + c;
}
addNumbers({a: 10, b:20}, 40); // Returns 70
I hope this made sense.
Piotr Migdał commented
@DrkSephy Thanks! Especially the last two lines were not obvious and new to me.