0

Taking a online course at udemy on JavaScript. Trying to code what I learned. I'm getting a undefined error. Visual Studio 2012 Pro saying the code is find but when I run the code I get the error.

        <script type="text/javascript">
        var numericalGrade = 82;
        var letterGrade;
        function myResaults() {
            document.write("Your score is " + numericalGrade + "%. Your grade will be a " + letterGrade + ".<br />");
        }

        if (numericalGrade >= 90) {
            letterGrade = "A";
            document.write(myResaults() + " Excellent, you passed this course with flying colors...");
        }

        else if (numericalGrade >= 80) {
            letterGrade = "B";
            document.write(myResaults() + " Excellent, you passed this course with a great grade..");

        }
        else if (numericalGrade >= 70) {
            letterGrade = "C";
            document.write(myResaults() + " Congratulations, you passed this course...");

        }
        else if (numericalGrade >= 60) {
            letterGrade = "D";
            document.write(myResaults() + " You revived a grade that will not permit you to pass this course. You can retake this course at a later date.");

        }
        else {
            letterGrade = "F";
            document.write(myResaults() + "You failed this course. You can retake this course at a later date.");

        }
    </script>

So what am I doing wrong. I'm very new at JavaScript coding.

2
  • 2
    What's the exact error? Commented Aug 16, 2013 at 20:05
  • 2
    myResaults() returns undefined since it has no return statement. When you do myResaults() + "" you are concatenating undefined to a string, so you see undefined. Commented Aug 16, 2013 at 20:10

1 Answer 1

3

Your function needs to return a value, but since it wasn't you were getting undefined instead.

Change:

function myResaults() {
    document.write("Your score is " + numericalGrade + "%. Your grade will be a " + letterGrade + ".<br />");
}

to

function myResaults() {
    return "Your score is " + numericalGrade + "%. Your grade will be a " + letterGrade + ".<br />";
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it work. I have no clue what return does. Maybe further in the course videos, the instructor will explain what return does. Thanks again.
Return does pretty much that, specifies a value to be returned to whatever called the function. See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. As the MDN docs show, "The expression to return. If omitted, undefined is returned instead."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.