SitePoint Sponsor

User Tag List

Results 1 to 18 of 18

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    Mar 2005
    Location
    Toronto
    Posts
    378
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to set default value for function parameter?

    Hi everyone,

    I am rather new to javascript. I've been searching now for quite a while trying to look for a way to give the default value to a function argument if it's not given. For example, in php one would do the follow:
    PHP Code:
    function func_name(foo 'default') {
    ...

    In the above case, if foo isn't supplied while calling for the function, then foo would default to 'default'. I have tried that in javascript, but it doesn't appear to be working, so I am wondering how should I do this in javascript? Thanks
    In search of the clouds...and maybe some work

  2. #2
    CSS & JS/DOM Adept bronze trophy
    Join Date
    Mar 2005
    Location
    USA
    Posts
    5,482
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No, JavaScript doesn't support that PHP way to do it.

    How to give default values for function arguments in JavaScript.
    We miss you, Dan Schulz.
    Learn CSS. | X/HTML Validator | CSS validator
    Dynamic Site Solutions
    Code for Firefox, Chrome, Safari, & Opera, then add fixes for IE, not vice versa.

  3. #3
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Another "default value" question? Something smells fishy

  4. #4
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This must in the top 3 asked questions this month


  5. #5
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    function func_name(foo) {
    foo= foo||default;

    }

  6. #6
    CSS & JS/DOM Adept bronze trophy
    Join Date
    Mar 2005
    Location
    USA
    Posts
    5,482
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, that's one way to do it, mrhoo. However, that doesn't work if you want foo to be able to have a value that evaluates to false.

    Yes, this question has been asked a lot in the last few weeks.
    We miss you, Dan Schulz.
    Learn CSS. | X/HTML Validator | CSS validator
    Dynamic Site Solutions
    Code for Firefox, Chrome, Safari, & Opera, then add fixes for IE, not vice versa.

  7. #7
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Oops.

    function func_name(foo) {
    foo= (foo != undefined)? foo : default;

    }

    0, false, NaN and the empty string ('') are each not equal to (!=) undefined .
    The same values, plus null are not equivilent to (!==) undefined.
    To coerce a default value only for func() and func(undefined):

    function func(foo){
    foo= (foo!== undefined)? foo: 'default';
    }
    Last edited by mrhoo; Apr 22, 2007 at 18:03. Reason: explanation

  8. #8
    CSS & JS/DOM Adept bronze trophy
    Join Date
    Mar 2005
    Location
    USA
    Posts
    5,482
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    mrhoo, don't you mean the following?

    Code:
    function func_name(foo) {
      foo= (tyepof(foo)!='undefined')? foo : 'default value';
    
    }
    We miss you, Dan Schulz.
    Learn CSS. | X/HTML Validator | CSS validator
    Dynamic Site Solutions
    Code for Firefox, Chrome, Safari, & Opera, then add fixes for IE, not vice versa.

  9. #9
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Kravvitz View Post
    mrhoo, don't you mean the following?

    Code:
    function func_name(foo) {
      foo = (tyepof(foo)!='undefined')? foo : 'default value';
    
    }
    No need to use the typeof, undefined is a primitive value. Better would have been to check for strict equality though
    Code:
    function func_name(foo) { 
        foo= (foo !== undefined)? foo : "default";
    }

  10. #10
    SitePoint Addict
    Join Date
    Mar 2005
    Location
    Toronto
    Posts
    378
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow I didn't realize that this question has been asked so much in the past while. MikeFoster, I can however guarantee you that there isn't a conspiracy on my side, don't know about others though

    Thanks for everyone's reply. The method actually worked. Oddly though, it was what I used, the only reason why is didn't work before was because I used the function in 'window.onload'. Could anyone explain why I can't give arguments to a function for window.onload please? Thanks a bunch.
    In search of the clouds...and maybe some work

  11. #11
    CSS & JS/DOM Adept bronze trophy
    Join Date
    Mar 2005
    Location
    USA
    Posts
    5,482
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Why do you want to give arguments to a window.onload event handler?

    Can you show us your code?
    We miss you, Dan Schulz.
    Learn CSS. | X/HTML Validator | CSS validator
    Dynamic Site Solutions
    Code for Firefox, Chrome, Safari, & Opera, then add fixes for IE, not vice versa.

  12. #12
    SitePoint Addict
    Join Date
    Mar 2005
    Location
    Toronto
    Posts
    378
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Kravvitz View Post
    Can you show us your code?
    Sure. As a beginner, this is my attempt at creating an active clock.

    HTML Code:
    function proc_time(id) {
    	var e = document.getElementById(id); 
    	var d = new Date(); 
    	var hour = fix_time(d.getHours()); 
    	var min = fix_time(d.getMinutes());
    	var sec = fix_time(d.getSeconds()); 
    	e.innerHTML = '<span id="hour">' + hour + '</span>:<span id="min">' + min + '</span>:<span id="sec">' + sec + '</span>';
    }
    		
    function display_time(check) { 
    	check = (check != undefined) ? check : 0; 
    	a.innerHTML = check; 
    			
    	if (check == 0) { 
    		proc_time('clock'); 
    		a.timeInterval = setInterval(function() { proc_time('clock'); } , 500); 
    	} else if (check == 1) { 
    		clearInterval(a.timeInterval); 
    	} 
    } 
    		
    window.onload = display_time; 
    Feel free to point out any beginner's bad coding practices. Help appreciated
    In search of the clouds...and maybe some work

  13. #13
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow I didn't realize that this question has been asked so much in the past while. MikeFoster, I can however guarantee you that there isn't a conspiracy on my side, don't know about others though

  14. #14
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I wasn't sure if this was implementation dependent, so I checked in
    the browsers I have installed.

    undefined returns equal to ('==') the undefined keyword,
    values that have not been defined, and null.
    All other values are not == undefined.

    The only change the equivilence ('===') operator enforces is
    that it distinguishes null values from undefined.

    If you do NOT want to treat null as if it were undefined, use '!==',
    otherwise use '!='.


    Code:
    var non=[0, false, NaN ,'',null, undefined];
    var tx= '0,false,NaN,"",null,undefined (keyword),'.split(/,/);
    var A=['Expressions with undefined',''], i=0, str='';
    
    while(i< 7){
    	if(tx[i]===undefined) tx[i]='~Really undefined~';
    	A.push('('+tx[i]+ ' != undefined) returns '+ (non[i] != undefined));
    	if(non[i] == undefined){
    		A.push('and ('+tx[i]+ ' !== undefined) returns '+ (non[i] !== undefined));
    	}
    	A.push('');
    	i++;
    }
    
    alert(A.join('\n'))

  15. #15
    CSS & JS/DOM Adept bronze trophy
    Join Date
    Mar 2005
    Location
    USA
    Posts
    5,482
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    kefeso, you could use an anonymous function:
    Code:
    window.onload = function(){
      display_time(0);
    }
    Pepejeria, versions of IE before 5.5 don't seem to support the undefined keyword.
    We miss you, Dan Schulz.
    Learn CSS. | X/HTML Validator | CSS validator
    Dynamic Site Solutions
    Code for Firefox, Chrome, Safari, & Opera, then add fixes for IE, not vice versa.

  16. #16
    SitePoint Addict
    Join Date
    Mar 2005
    Location
    Toronto
    Posts
    378
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Kravvitz View Post
    kefeso, you could use an anonymous function
    Hi Kravvitz,

    Thanks for the advice. However, I am just wondering why couldn't give parameters directly there? I just want to figure out the mechanism behind it. Thanks.
    In search of the clouds...and maybe some work

  17. #17
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    @ Kravvitz, yeah, this was added to IE in version 5.5

  18. #18
    CSS & JS/DOM Adept bronze trophy
    Join Date
    Mar 2005
    Location
    USA
    Posts
    5,482
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You're welcome

    I'll try to explain how it works...

    Let's say we have a function that we want to assign as an event handler.
    Code:
    function loadHandler(){
      alert('the page has finished loading');
    }
    If we use what is shown in the following code block, then the function is executed when this statement is evaluated and whatever value that the function returns will be set as the event handler. (If we had a function that returned a function it would be a different matter.) Whether we pass any arguments in this function call or not doesn't matter.
    Code:
    window.onload = loadHandler();
    Now if we use this then we are passing a reference to the function which will be used to call it when the event is triggered.
    Code:
    window.onload = loadHandler;
    We could also do the following, which is to use an anonymous function to contain calls to other functions and/or other statements. We set the anonymous function as the event handler so that when the event is triggered the contents of the function will be executed. This also allows us to pass arguments if we want to do so.
    Code:
    window.onload = function(){
      loadHandler();
      alert('hello world');
    }
    @ Pepejeria, that's why I use typeof instead. It works fine and allows me to support a few more, although very old, browsers.
    We miss you, Dan Schulz.
    Learn CSS. | X/HTML Validator | CSS validator
    Dynamic Site Solutions
    Code for Firefox, Chrome, Safari, & Opera, then add fixes for IE, not vice versa.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •