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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Dont do this
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""NaNfalsenullundefinedA safer way to check for the presence of the parameter is:
Edit 2:
The previous function is not 100% secure since someone (an idiot probably) could define
undefinedmaking the function to behave unexpectedly. This is a final, works-anywhere, bulletproof version: