Why isn't this script working???

Discussion in 'JavaScript' started by solid7, Oct 20, 2013.

  1. #1
    
    <script type="text/javascript">
    function getAgeYears() {
    "use strict";
    var dobYear = 1987,
    dobMonth = 1,
    dobDay = 22,
    now = new Date(),
    nowYear = now.getFullYear(),
    nowMonth = now.getMonth() + 1,
    nowDay = now.getDate(),
    yrAge = nowYear - dobYear;
    if (nowMonth < dobMonth) {yrAge--; } else if (nowMonth === dobMonth && nowDay < dobDay) {yrAge--;
    return yrAge; }
    document.write(getAgeYears());
    }
    
    Code (markup):
    I will admit that I'm a novice coder, but I can't get this to work for the life of me. Any help is appreciated.
     
    solid7, Oct 20, 2013 IP
  2. rehan.khalid.9235

    rehan.khalid.9235 Active Member

    Messages:
    78
    Likes Received:
    2
    Best Answers:
    1
    Trophy Points:
    85
    #2
    here's what i found about your code, seems to be a logical error.

    on line 15
    document.write(getAgeYears());

    this will make your function a 'recursive function' . you are calling this inside your function. remove it and place it outside the function.

     <script type="text/javascript">
                function getAgeYears() {
    
                    var dobYear = 1987,
                    dobMonth = 1,
                    dobDay = 22,
                    now = new Date(),
                    nowYear = now.getFullYear(),
                    nowMonth = now.getMonth() + 1,
                    nowDay = now.getDate(),
                    yrAge = nowYear - dobYear;
                    if (nowMonth < dobMonth) {yrAge--; }
                    else if (nowMonth === dobMonth && nowDay < dobDay)
                    {
                        yrAge--;                   
                    }
                   
                    return yrAge;
                   
                }
             
                document.write(getAgeYears());
            </script>
    HTML:
     
    rehan.khalid.9235, Oct 21, 2013 IP
  3. solid7

    solid7 Well-Known Member

    Messages:
    459
    Likes Received:
    51
    Best Answers:
    0
    Trophy Points:
    148
    #3
    Yes, I have tried that. I still get no output from the script.
     
    solid7, Oct 21, 2013 IP
  4. rehan.khalid.9235

    rehan.khalid.9235 Active Member

    Messages:
    78
    Likes Received:
    2
    Best Answers:
    1
    Trophy Points:
    85
    #4
    have you tried my code? as i tested it and it display age . please copy my code and run it.

    another bug in your code is statement of 'return' in else{} body. it should be at the end of function
     
    rehan.khalid.9235, Oct 21, 2013 IP