Empty Function Parameters

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • empiresolutions
    New Member
    • Apr 2006
    • 162

    Empty Function Parameters

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

    Code:
    function color_input(id,token){
    
        if (!empty(token)){
            document.getElementById(id).style.backgroundColor = '#2A2A2A';
            document.getElementById(id).style.color = '#DDC58C';
        }else{
            document.getElementById(id).style.backgroundColor = '';
            document.getElementById(id).style.color = '';
        }
    
    }
    Called in HTML like

    [code=HTML]<input type="text" id="example_nam e" onblur="color_i nput('example_n ame');">[/code]

    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=''

    Code:
    function color_input(id,token=''){}
    How do i set a default param in a JS function?
    Last edited by gits; Jan 28 '09, 12:24 AM. Reason: fix code tags
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    here is a short example:

    Code:
    function foo(param) {
        // when param is missing set a default-value
        if (typeof param == 'undefined') {
            param = 'default_value';
        }
    }
    kind regards

    Comment

    • Dormilich
      Recognized Expert Expert
      • Aug 2008
      • 8694

      #3
      another variation thereof is:
      Code:
      function foo(param) {
          param = param || 'default_value';
      }

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        No, that would be unreliable with any falsy arguments - see http://bytes.com/topic/javascript/an...tion-arguments

        Comment

        • Dormilich
          Recognized Expert Expert
          • Aug 2008
          • 8694

          #5
          I've seen this appoach mostly in cases, where you test for an object.

          Comment

          • acoder
            Recognized Expert MVP
            • Nov 2006
            • 16032

            #6
            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.

            Comment

            • Dormilich
              Recognized Expert Expert
              • Aug 2008
              • 8694

              #7
              that is correct.

              (20 chars min)

              Comment

              • empiresolutions
                New Member
                • Apr 2006
                • 162

                #8
                thanks much for the insight.

                This will be adding this to my function.
                Code:
                if (typeof token != 'undefined')

                Comment

                Working...