pelegk1
07-27-2004, 05:58 AM
can a JS function have default values like in c++ for email
func1(x,y=3){
}
thanks in advance
peleg
func1(x,y=3){
}
thanks in advance
peleg
|
Click to See Complete Forum and Search --> : does JS function recive default values? pelegk1 07-27-2004, 05:58 AM can a JS function have default values like in c++ for email func1(x,y=3){ } thanks in advance peleg AdamGundry 07-27-2004, 06:04 AM No, you can't set default values as such, but you can allow a variable number of arguments. If you pass fewer arguments than the function prototype expects, the remaining values are set to undefined. This allows you to do this: function func1(x, y){ if (typeof y = 'undefined') y = 3; ... } Adam BillyRay 07-27-2004, 06:05 AM I normally use this for defaulting values: function wibble(foo, bar) { var newBar = bar || 500; // here, 500 is the default value if bar is not passed in } Hope this helps, Dan AdamGundry 07-27-2004, 06:08 AM That's probably fine for most cases, however watch out if you are likely to pass values that evaluate to false. For example, if you call wibble(5, 0) then newBar will have the value 500, not 0 as might be expected. Whether this matters does of course depend on the script. Adam BillyRay 07-27-2004, 06:24 AM Good point - for what I was using it for, I never needed to pass false. Incidentally, you're missing an equals sign. This: if (typeof y = 'undefined') y = 3; should read like this: if (typeof(y) == 'undefined') y = 3; Dan BillyRay 07-27-2004, 06:25 AM (And I know you don't need the extra brackets - but I added them anyway ;o) Dan AdamGundry 07-28-2004, 02:55 AM Well spotted. :o Adam webdeveloper.com
Copyright Internet.com Inc., All Rights Reserved. |