P-RAD P-RAD - 1 year ago 92
Javascript Question

ES6 with default arguments : Whether a parameter is passed in or not

function myfunc( value1, value2='defaultValue' ) {
//some stuff

How will I know that if a parameter is passed in or not into a function. I know that the default value will be set if you don't pass in anything as argument.I actually want to check if the user is passing anything as a 2nd parameter ( even if it is same as the default value ) and change my return value accordingly.

I was checking out ES6 docs and this SO answer , Not really what I am looking for.


Answer Source

arguments still represents the actual arguments you were sent, so arguments.length will give you that information.

function myfunc( value1, value2='defaultValue' ) {
  console.log("value1", value1);
  console.log("value2", value2);
  console.log("length", arguments.length);

On a compliant JavaScript engine, that outputs

value1 foo
value2 defaultValue
length 1

arguments will not work in an arrow function, though, and estus posted a good alternative that does.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download