469,361 Members | 2,294 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,361 developers. It's quick & easy.

Empty Function Parameters

162 100+
How do i declare a default value in a function? I have a simple function

Expand|Select|Wrap|Line Numbers
  1. function color_input(id,token){
  2.  
  3.     if (!empty(token)){
  4.         document.getElementById(id).style.backgroundColor = '#2A2A2A';
  5.         document.getElementById(id).style.color = '#DDC58C';
  6.     }else{
  7.         document.getElementById(id).style.backgroundColor = '';
  8.         document.getElementById(id).style.color = '';
  9.     }
  10.  
  11. }
  12.  
Called in HTML like

Expand|Select|Wrap|Line Numbers
  1. <input type="text" id="example_name" onblur="color_input('example_name');">
You will notice that the #2 parameter is missing in the html call. Sometimes i don't have it to send. in PHP i would just set the functions second param like token=''

Expand|Select|Wrap|Line Numbers
  1. function color_input(id,token=''){}
How do i set a default param in a JS function?
Jan 27 '09 #1
7 7857
gits
5,390 Expert Mod 4TB
here is a short example:

Expand|Select|Wrap|Line Numbers
  1. function foo(param) {
  2.     // when param is missing set a default-value
  3.     if (typeof param == 'undefined') {
  4.         param = 'default_value';
  5.     }
  6. }
kind regards
Jan 28 '09 #2
Dormilich
8,652 Expert Mod 8TB
another variation thereof is:
Expand|Select|Wrap|Line Numbers
  1. function foo(param) {
  2.     param = param || 'default_value';
  3. }
Jan 28 '09 #3
acoder
16,027 Expert Mod 8TB
No, that would be unreliable with any falsy arguments - see http://bytes.com/topic/javascript/an...tion-arguments
Jan 28 '09 #4
Dormilich
8,652 Expert Mod 8TB
I've seen this appoach mostly in cases, where you test for an object.
Jan 28 '09 #5
acoder
16,027 Expert Mod 8TB
It'll work in those cases, but where the variable evaluates to false, e.g. false, 0, "", it will take the default instead of the actual value passed.
Jan 28 '09 #6
Dormilich
8,652 Expert Mod 8TB
that is correct.

(20 chars min)
Jan 28 '09 #7
empiresolutions
162 100+
thanks much for the insight.

This will be adding this to my function.
Expand|Select|Wrap|Line Numbers
  1. if (typeof token != 'undefined')
Jan 28 '09 #8

Post your reply

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

Similar topics

1 post views Thread by Scott M. Lyon | last post: by
1 post views Thread by Scott M. Lyon | last post: by
reply views Thread by jennifer.perkins | last post: by
5 posts views Thread by Mark Olbert | last post: by
1 post views Thread by =?Utf-8?B?RG9u?= | last post: by
10 posts views Thread by arnuld | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.