Friday 8 June 2018

javascript - Default vars in a method?




Here's my method:



p.show = function(message, status, timer){

//do stuff
};



Is there a way, so that if vars such as timer are not passed in, to have a default for them, e.g, true.



In php I would do it like:



private function show(message, status, timer = true){
}

Answer



Yes, the logical equivalent is to test the length of the arguments array-like object:




p.show = function(message, status, timer){
if (arguments.length < 3 )
timer = 1000; // default value
//do stuff
};


If you want to set it to the default value even if it's manually passed in, but undefined is passed in for the value, you can also use:




p.show = function(message, status, timer){
if (timer === undefined)
timer = 1000;
//do stuff
};


A more common way is to just use timer = timer || 1000; which will set timer to 1000 if it has a falsy value to begin with, so if someone passes in no third argument, or if they pass in 0, it will still be set to 1000, but if they pass in a truthy value like 50 or an object, it will keep that value.



In future versions of Javascript (ES6), you will be able to use default arguments the way you are used to from PHP:




p.show = function(message, status, timer = 1000){
//do stuff
};

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...