Hello,
I have a function that I want to pass an argument to, however I want it to default to 0.
Is it possible todo it similarly to PHP, like:
function byMonth(export=0) {
Many thanks
Hello,
I have a function that I want to pass an argument to, however I want it to default to 0.
Is it possible todo it similarly to PHP, like:
function byMonth(export=0) {
Many thanks
You can set a default inside, like this:
function byMonth(export) {
export = export || 0;
//your code
}
Dont do this
function byMonth(export){
export = export || 0;
alert(export);
}
Edit:
The previous version has a silent bug, I'm leaving it just as an example of what NOT TO DO.
The problem is, suppose you pass the function the argument false
, it will take the default value although you actually called it with an argument.
All this other parameters will be ignored and the default will be used (because of javascript concept of falsy)
0
""
NaN
false
null
undefined
A safer way to check for the presence of the parameter is:
function byMonth(export){
if(export === undefined) export = 0;
}
Edit 2:
The previous function is not 100% secure since someone (an idiot probably) could define undefined
making the function to behave unexpectedly. This is a final, works-anywhere, bulletproof version:
function byMonth(export){
var undefined;
if(export === undefined) export = 0;
}