By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,521 Members | 1,274 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,521 IT Pros & Developers. It's quick & easy.

Default function arguments

Markus
Expert 5K+
P: 6,050
Is it possible to set default arguments for functions like you are able to in PHP?

Like so:

Expand|Select|Wrap|Line Numbers
  1. function(type = 'default', default = 'argument')
  2. // ...
  3.  
?

Cheers guys
May 21 '08 #1
Share this Question
Share on Google+
7 Replies


gits
Expert Mod 5K+
P: 5,390
hi ...

not like that ... but you may use:

Expand|Select|Wrap|Line Numbers
  1. function my_func(arg0) {
  2.     // if arg0 is not passed to my_func 
  3.     if (typeof arg0 == 'undefined') {
  4.         arg0 = 'default_val0';
  5.     }
  6.  
  7.     // now use arg0 and further code
  8. }
kind regards
May 21 '08 #2

Markus
Expert 5K+
P: 6,050
hi ...

not like that ... but you may use:

Expand|Select|Wrap|Line Numbers
  1. function my_func(arg0) {
  2.     // if arg0 is not passed to my_func 
  3.     if (typeof arg0 == 'undefined') {
  4.         arg0 = 'default_val0';
  5.     }
  6.  
  7.     // now use arg0 and further code
  8. }
kind regards
Yeh, thought that might be the case.
Was just looking for a prettier alternative ^_^
May 21 '08 #3

acoder
Expert Mod 15k+
P: 16,027
This should hopefully be supported in the next major version of JavaScript/ECMAScript or something similar. In the meantime, you could use something like this.
May 21 '08 #4

rnd me
Expert 100+
P: 427
Expand|Select|Wrap|Line Numbers
  1. function shout(message){
  2.      alert( message || "hello world" )
  3. }
May 22 '08 #5

acoder
Expert Mod 15k+
P: 16,027
That's effective in most cases,but if you pass null, false, 0, empty string, etc. it will return "hello world" which is probably not what you want.
May 22 '08 #6

rnd me
Expert 100+
P: 427
That's effective in most cases,but if you pass null, false, 0, empty string, etc. it will return "hello world" which is probably not what you want.
thats a good point. any falsy -evaluating variable would trigger the default.

if you want the defaults only upon undefineds, try something like:

Expand|Select|Wrap|Line Numbers
  1.   function shout(message){
  2.     alert( message != undefined ? message : "hello world" )
  3.   }
  4.  
May 22 '08 #7

100+
P: 428
Expand|Select|Wrap|Line Numbers
  1. function (message){
  2.          message= (message !== undefined)? message : "default" ;
  3. }
!== not equal and same type
May 23 '08 #8

Post your reply

Sign in to post your reply or Sign up for a free account.