<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.
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:
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