1

How can I get the value of the default parameters/arguments dynamicly without using the parameter variable?

function someFunc(param1 = 'value', param2 = 'value') {
    console.log(arguments.length);
    console.log(arguments[0]);
}

someFunc(); //0 undefined
1
  • 2
    I smell an XY Problem. What are you trying to do exactly? Why do you need to read the default values inside the function? Commented Apr 27, 2015 at 7:33

2 Answers 2

1

I wanted to do the same, in order to assign several attributes to the instance of my class.

This approach might not help you since it uses one object argument instead of two arguments, still worth to mention:

class MyClass{
  constructor(params={param1:3.1415, param2:'Hello'}){
    //*assign* effectively destructures the params arg
    Ojbect.assign(this,params);
  }
}

Similarly your example would look like this:

function someFunc(params = {param1:'value', param2: 'value'}) {
    console.log(Object.keys(params).length);
    console.log(params['param1']);
}

Note that this approach requires your argument to be an object and that given one of the two arguments the other one will not be present in the default object.

Sign up to request clarification or add additional context in comments.

Comments

0

You don't. Think about it this way. How do you get the default value with the old method?

function someFunc(param1, param2) {
    param1 = param1 || 'value';
    param2 = param2 || 'value';

    console.log(arguments.length);
    console.log(arguments[0]);
}

someFunc(); //0 undefined

Your best bet is to store the default value in a variable, and compare it in runtime. But that is kind of pointless.

Comments

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.