Is there a way to get the default value of x
here?
No, there is no built-in reflection function to do such things, and it is completely impossible anyway given how default parameters are designed in JavaScript.
Note that toString()
ing the function would not work as it would break on defaults that are not constant.
Indeed. Your only way to find out is to call the function, as the default values can depend on the call. Just think of
function(x, y=x) { … }
and try to get sensible representation for y
s default value.
In other languages you are able to access default values either because they are constant (evaluated during the definition) or their reflection allows you to break down expressions and evaluate them in the context they were defined in.
In contrast, JS does evaluate parameter initializer expressions on every call of the function (if required) - have a look at How does this
work in default parameters? for details. And these expressions are, as if they were part of the functions body, not accessible programmatically, just as any values they are refering to are hidden in the private closure scope of the function.
If you have a reflection API that allows access to closure values (like the engine's debugging API), then you could also access default values.
It's quite impossible to distinguish function(x, y=x) {…}
from function(x) { var y=x; …}
by their public properties, or by their behaviour, the only way is .toString()
. And you don't want to rely on that usually.