Order of default parameter values ​​important to es6?

I hope to clarify something.

ES6 provides advanced parameter handling and allows you to pass default parameter values.

function f (x, y = 7, z = 42) {
    return x + y + z
}

f(1) === 50

      

This works great. However, if I change the arguments to look like this: (x = 7, y, z = 42)

returns NaN

.

function f (x = 7, y, z = 42) {
    return x + y + z
}

f(1) === 50

      

Can someone explain why this is happening?

+3


source to share


1 answer


Order matters when you pass values ​​to a function. In the first case, you only pass one variable to the function. This value will be assigned to the variable x

. Since you are only passing one variable, the rest of the values ​​for other parameters are considered null. However, since you assigned default values ​​for these parameters, the function will try to evaluate 1 + 7 + 52

, which resolves to 50.



In your second case, you are passing 1 as the value of the variable x

. Since the parameter y

remains unassigned, so the function will evaluate 1 + undefined + 42

which is the type NaN

.

0


source







All Articles