Tuesday 31 January 2017

How can I declare optional function parameters in Javascript?











Can I declare default parameter like



function myFunc( a, b=0) 
{
// b is my optional parameter

}


in javascript.


Answer



With ES6: This is now part of the language:



function myFunc(a, b = 0) {
// function body
}



Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).






With ES5:



function myFunc(a,b) {
b = b || 0;


// b will be set either to b or to 0.
}


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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...