2

Thanks for taking time to review this question. I've been trying to fix a problem for one or two hours with no success...

I have a web page that sets a JavaScript variable based on the response from a function:

grade = getScore(questionAnswer, userAnswer, questionType);

(userAnswer is the user's answer to a question and is retrieved from a textarea)

Here is getScore:

function getScore(questionAnswer, userAnswer, questionType) {

    switch(questionType) {
        case 'multiplechoice':
            return scoreMC(questionAnswer, userAnswer);
        break;

        case 'usertypesanswer':
            return scoreTA(questionAnswer, userAnswer);         
        break;

        default:
            return 0
    }   

}

The functions for scoreMC and scoreTA have been tested thoroughly and work great. The issue is that if a user's answer is not formatted correctly, scoreMC or scoreTA will return false. Otherwise it returns the values score and msg. However, instead of getting a "false" value for "grade" when I set the value of the grade variable based on the getScore function, I get "undefined". (We have no problems when the user response validates properly.)

After setting "grade", I have tried to check if any part of it is undefined:

if(typeof(grade.score) !== undefined)

I do not understand why, but even when I see "undefined" in my Firebug console, grade.score passes this check...

Does anyone see what I am doing wrong? Thank you very much for your assistance. I have a lot to learn about JavaScript.

1
  • have you tried without the typeof Commented Sep 24, 2011 at 0:20

2 Answers 2

3
if(typeof(grade.score) !== undefined)

can be

if(grade.score && grade.score !== false) // if I understand your question 

or

if(typeof(grade.score) !== "undefined")

typeof returns a string

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Thanks so much! I knew it had to be simple. :) I used "if(grade.score && grade.score !== false)" as you suggested and it worked.
0

If no return statement is used (or an empty return with no value), JavaScript returns undefined.

It is almost certain that one of your score functions (scoreMC, scoreTA, whose code you should have included in the question) does not return a value i.e.

return;

Or just reaches the end of the function code block without encountering a return.

Comments

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.