Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Thanks,

like image 949
P-RAD Avatar asked Dec 05 '22 16:12

P-RAD


1 Answers

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);
}
myfunc("foo");

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.

like image 101
T.J. Crowder Avatar answered May 17 '23 08:05

T.J. Crowder