Friday, June 22, 2018

Default argument values in JavaScript functions










in PHP:




function func($a = 10, $b = 20){
// if func() is called with no arguments $a will be 10 and $ b will be 20
}


How can you do this in JavaScript?



I get a error if I try to assign values in function arguments





missing ) after formal parameters



Answer



In javascript you can call a function (even if it has parameters) without parameters.



So you can add default values like this:



function func(a, b){
if (typeof(a)==='undefined') a = 10;
if (typeof(b)==='undefined') b = 20;


//your code
}


and then you can call it like func(); to use default parameters.



Here's a test:



function func(a, b){

if (typeof(a)==='undefined') a = 10;
if (typeof(b)==='undefined') b = 20;

alert("A: "+a+"\nB: "+b);
}
//testing
func();
func(80);
func(100,200);


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...