A workaround implementation of setting default values for js function parameters

  • 2020-03-30 03:02:55
  • OfStack

A handy use of PHP is to define functions by setting default values for parameters, such as:
function simue ($a=1,$b=2){ 
return $a+$b; 
echo simue(); //The output of 3
echo simue(10); //The output of 12
echo simue(10,20); //The output of 30

Function simue(a=1,b=2){} will indicate a missing object.

The js function has arguments, an array of arguments that the compiler stores one by one. Therefore, our js version can support the function of parameter default value through another alternative method, modify the above example:
function simue (){ 
var a = arguments[0] ? arguments[0] : 1; 
var b = arguments[1] ? arguments[1] : 2; 
return a+b; 
alert( simue() ); //The output of 3
alert( simue(10) ); //The output of 12
alert( simue(10,20) ); //The output of 30

Related articles: