1

Let's say you have

var funct=function(a,b){
    return a+b;
};
console.log(funct);

Is there any way you can get the names of the arguments (a and b) from funct? If you are with in the function do you have any access to them? I know "arguments" gives you an array-like object, but is there anything that gives you a map-like or object-like representation of the arguments so that you can get their names when the function was declared?

2
  • 4
    Why would you need that? Commented Jun 14, 2012 at 16:03
  • 1
    You can already access the arguments to a function by name by using the actual names – it's probably best to use the argument object to implement variadic functions. If you want dynamic named arguments, use the options-hash pattern. (The one jQuery and other libraries use pervasively.) Commented Jun 14, 2012 at 16:04

2 Answers 2

5

No, you cannot do this. There's no way to get the name of variable as a string.

If you really need this, I suggest instead of passing multiple parameters, pass an object.

var funct=function(args){
    var argsNames = Object.keys(args); // Get the keys of the args object
    console.log(argsNames); // ['a','b']
    return args.a + args.b;
};

Then call it like so:

funct({
    a: 12,
    b: 2
});
Sign up to request clarification or add additional context in comments.

3 Comments

could make use of object.keys this way as well: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
@WaqarAlamgir: What are you talking about?
@sherlocken: Thanks, I'll add that to the answer.
2

One way is to turn the function into a string and parse it out

var funct=function(a,b){
    return a+b;
};
var re = /\(([^)]*)/;
var daArgs = funct.toString().match(re)[1].split(/,\s?/);
console.log(daArgs);

jsFiddle

Still have no clue why you would need it.

2 Comments

I assumed he wanted the argument names inside the function, not outside.
@Rocket Than replace funct.toString() with the deprecated arguments.callee.toString(), but it will not run in strict mode. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.