16

Is there a way to retrieve a function's default argument value in JavaScript?

function foo(x = 5) {
    // things I do not control
}

Is there a way to get the default value of x here? Optimally, something like:

getDefaultValues(foo); // {"x": 5}

Note that toStringing the function would not work as it would break on defaults that are not constant.

Tushar
  • 85,780
  • 21
  • 159
  • 179
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • [Python](http://stackoverflow.com/questions/12627118/get-a-function-arguments-default-value), [Ruby](http://ruby-doc.org/core-2.2.0/Method.html#method-i-parameters) and [C#](https://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo.defaultvalue(v=vs.110).aspx) all do this by the way. – Benjamin Gruenbaum Oct 04 '15 at 14:43
  • 1
    check this http://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function – Or Bachar Oct 04 '15 at 14:54
  • 5
    @OrBachar That is the question of _set_ default parameter, here OP want to **get** default parameter value from outside of the function without calling it. – Tushar Oct 04 '15 at 14:56
  • 1
    what is the use case ? – Mulan Oct 04 '15 at 18:50
  • What are you trying to do? This reminds me of [Building a LINQ-like query API in JavaScript](http://stackoverflow.com/q/31198105/1048572) – Bergi Oct 11 '15 at 12:27

4 Answers4

6

Since we don't have classic reflection in JS, as you can find on C#, Ruby, etc., we have to rely on one of my favorite tools, regular expressions, to do this job for us:

let b = "foo";
function fn (x = 10, /* woah */ y = 20, z, a = b) { /* ... */ }

fn.toString()
  .match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1] // Get the parameters declaration between the parenthesis
  .replace(/(\/\*[\s\S]*?\*\/)/mg,'')             // Get rid of comments
  .split(',')
  .reduce(function (parameters, param) {          // Convert it into an object
    param = param.match(/([_$a-zA-Z][^=]*)(?:=([^=]+))?/); // Split parameter name from value
    parameters[param[1].trim()] = eval(param[2]); // Eval each default value, to get strings, variable refs, etc.

    return parameters;
  }, {});

// Object { x: 10, y: 20, z: undefined, a: "foo" }

If you're going to use this, just make sure you're caching the regexs for performance.

Thanks to bubersson for hints on the first two regexs

Community
  • 1
  • 1
pilau
  • 6,635
  • 4
  • 56
  • 69
  • 2
    This breaks if the environment isn't the same: `function foo(){ var x = 5; return function bar(y = x){}}; var bar = foo();` – Benjamin Gruenbaum Oct 05 '15 at 08:48
  • Not true. You could still use `.toString()` on that returned function. – pilau Oct 05 '15 at 08:51
  • 3
    No, because you would have to evaluate it, and that would cause a side effect. For example `function foo(){ var x = prompt("Please enter a number"); return function (y = x) {}; } var bar = foo()` - how would you extract the value `y` is bound to here? – Benjamin Gruenbaum Oct 05 '15 at 08:55
  • I understand, but how do you expect to get around an inherent limitation of the language? It's as if you'd ask "how to get a scoped variable outside of its closure" – pilau Oct 05 '15 at 08:58
  • Well, hopefully there is an API in ES2015 or ES2016 or something planned (or a reason it was rejected) that lets you do `Reflect.getDefaultParameterValues` on a function or something similar. This is not really unexpected as other dynamically typed languages with default parameters like Python and Ruby and PHP can do this and so can statically typed ones like C# or Scala. It would certainly be unexpected to not be able to do this. – Benjamin Gruenbaum Oct 05 '15 at 09:06
  • Sorry, I wasn't aware you were looking for a ES2016 contribution via this answer, I thought I should merely attempt solving your problem using code that can work right now. – pilau Oct 05 '15 at 09:12
  • Why are you so sure that there is no code that does this right now :) I would not be surprised if there is an obscure method that does this that I'm just not aware of :) – Benjamin Gruenbaum Oct 05 '15 at 09:13
  • Because I'm pretty confident of my JS skeelz :) But I'll be more than happy to learn something new and eat my hat doing so! – pilau Oct 05 '15 at 09:15
3

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 ys 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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • " it is completely impossible anyway given how default parameters are designed in JavaScript." - well that part is wrong. Your `Reflect.getDefaultParameterValues` could return getters for the parameters. – Benjamin Gruenbaum Oct 11 '15 at 15:26
  • You mean it should return an object that upon evaluation executes side effects (the default initializer expression) and then throws an error like "`x is not defined`"? This is similarly impossible as getting closed-over values from a closure function object - it is thinkable, but not designed to be. – Bergi Oct 11 '15 at 16:49
1

I'd tackle it by extracting the parameters from a string version of the function:

// making x=3 into {x: 3}
function serialize(args) {
  var obj = {};
  var noWhiteSpace = new RegExp(" ", "g");
  args = args.split(",");
  args.forEach(function(arg) {
    arg = arg.split("=");
    var key = arg[0].replace(noWhiteSpace, "");
    obj[key] = arg[1];
  });
  return obj;
  }

 function foo(x=5, y=7, z='foo') {}

// converting the function into a string
var fn = foo.toString();

// magic regex to extract the arguments 
var args = /\(\s*([^)]+?)\s*\)/.exec(fn);

//getting the object
var argMap = serialize(args[1]); //  {x: "5", y: "7", z: "'foo'"}

argument extraction method was taken from here: Regular Expression to get parameter list from function definition

cheers!

PS. as you can see, it casts integers into strings, which can be annoying at times. just make sure you know the input type beforehand or make sure it won't matter.

Community
  • 1
  • 1
silicakes
  • 6,364
  • 3
  • 28
  • 39
  • This does not work if the function is bound to anything but a literal. For example `let y = 5; function foo(x=y) {};`. This is unlike the Python Ruby or C# solutions. – Benjamin Gruenbaum Oct 04 '15 at 15:03
  • @BenjaminGruenbaum This won't work in C# either. it has to be compile time constant.http://i.imgur.com/WWDwPnC.png – Royi Namir Oct 04 '15 at 15:13
  • depending on your situation, you can tap that by using something like obj[key] = eval(arg[1]) || arg[1]; in the serialization fn. yeah, eval.. but that's actually a reasonable solution – silicakes Oct 04 '15 at 15:13
  • @RoyiNamir it's completely valid JavaScript though. It compiles and the default parameter works - but the code in this answer does not return the correct default value. – Benjamin Gruenbaum Oct 04 '15 at 15:14
  • @silicakes that would fail for cases where the lexical environment isn't the same. Not to mention `this`. I was hoping for more of a `Reflect.getDefaultArguments` or something like that, we've had some discussion of edge cases starting here: http://goo.gl/iqx5yf – Benjamin Gruenbaum Oct 04 '15 at 15:15
  • I was referring to _let y = 5; function foo(x=y) {}; This is unlike the Python Ruby or C# solutions_. In C# declaring default value to another variable is an error. – Royi Namir Oct 04 '15 at 15:15
  • @RoyiNamir no need to be a nitpick, `const int y = 6; int Bar(int x = y){ return x;}` runs just fine in LINQPad and reflection gets out the correct values. – Benjamin Gruenbaum Oct 04 '15 at 15:26
  • 1
    @BenjaminGruenbaum I'm not.Please be precise on what you write examples about and about analogy to C#. I Just tested the code and if that wasn't a CONST - it wouldn't compile . So it can not be a dynamic variable. in your example - `let` can have dynamic/calculated value. This is a huge difference. – Royi Namir Oct 04 '15 at 15:28
1

As the question states, using toString is a limited solution. It will yield a result that could be anything from a value literal to a method call. However, that is the case with the language itself - it allows such declarations. Converting anything that's not a literal value to a value is a heuristic guess at best. Consider the following 2 code fragments:

let def;
function withDef(v = def) {
  console.log(v);
}

getDefaultValues(withDef); // undefined, or unknown?

def = prompt('Default value');
withDef();
function wrap() {
  return (new Function(prompt('Function body')))();
  // mutate some other value(s) --> side effects
}

function withDef(v = wrap()) {
  console.log(v);
}
withDef();
getDefaultValues(withDef); // unknown?

While the first example could be evaluated (recursively if necessary) to extract undefined and later to any other value, the second is truly undefined as the default value is non-determinitic. Of course you could replace prompt() with any other external input / random generator.

So the best answer is the one you already have. Use toString and, if you want, eval() what you extract - but it will have side effects.

Amit
  • 45,440
  • 9
  • 78
  • 110