Friday 22 June 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...