Can I declare default parameter like
function myFunc( a, b=0)
{
// b is my optional parameter
}
in JavaScript?
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.
With ES6: This is now part of the language:
Please keep in mind that ES6 checks the values against
undefinedand not against truthy-ness (so only real undefined values get the default value – falsy values like null will not default).With ES5:
This works as long as all values you explicitly pass in are truthy.
Values that are not truthy as per MiniGod’s comment:
null, undefined, 0, false, ''It’s pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.