Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order of default parameter values important es6?

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?

like image 429
peter flanagan Avatar asked Apr 18 '17 09:04

peter flanagan


1 Answers

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.

like image 149
Mμ. Avatar answered Oct 22 '22 12:10

Mμ.