I am hoping to clarify something.
ES6 brings us extended parameter handling and enables us to pass default parameter values.
function f (x, y = 7, z = 42) {
return x + y + z
}
f(1) === 50
This works fine. However, if I swap the arguments so they look like this (x = 7, y, z = 42)
it returns NaN
.
function f (x = 7, y, z = 42) {
return x + y + z
}
f(1) === 50
Can anyone explain why this is happening?
The order matters when you are passing the values into the function. In the first case, you are passing only one variable to the function. That value will be assigned to variable x
. Since you are only passing one variable, the rest of the values for the other parameters are assumed to be null. However, since you have assigned default values for those parameters, the function would try to evaluate 1 + 7 + 52
, which resolves to 50.
In your second case, You are passing 1 as the value for variable x
. Since parameter y
is left unassigned, therefore the function will evaluate 1 + undefined + 42
, which is a NaN
type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With