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
Setting JavaScript default parameters for a function In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will have the default values of undefined .
Default parameter in JavascriptThe default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
From ES6/ES2015, default parameters are in the language specification. just works. Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. function foo(a, b) { a = typeof a !==
A JavaScript function does not perform any checking on parameter values (arguments).
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With