Is it possible to have default parameters in javascript functions like you can in other laguages such as PHP? I would like to do something like this:
function setTagHoverColor( tagType, className, color = "#FFFF00" )
{
}
| SitePoint Sponsor |
Is it possible to have default parameters in javascript functions like you can in other laguages such as PHP? I would like to do something like this:
function setTagHoverColor( tagType, className, color = "#FFFF00" )
{
}




unfortunately, no such capability in this point of time, but you can always do this
Code:function setTagHoverColor( tagType, className, color ) { if (color == undefined) { color = "#FFFF00"; } }





The if is not needed:
Code:function setTagHoverColor(tagType, className, color) { color = color || "#ff0"; }





The latter won't work if 0 is an allowed parameter value. "Undefined" check looks cleaner, though more verbose.





True, though color expects a String. You would basically need check to check that as well if you wanna be bulletproof. Somebody might pass a function, null, object etc...





I wonder what is driving this question? I thought I had seen the exact same question before, quite recently.
http://www.sitepoint.com/forums/show...54#post3347854





Ah right, and I replied to that one as well. I am apparently senile.





Different guy asking the question this time though.
Which begs the question - does nobody bother with the search function anymore?![]()




furthermore if we have functions that may contain unlimited parameters for example
function x(a,b,c*) {
}
x(1,2,3) // call with parameter 1,2,3
x(1,2,3,4) // call with parameter 1,2,3,4
this will need to deal with special variable call argument and special method call apply.Haven't really explore deeply into it yet.
Bookmarks