Help On Javascript

Hi guys.I am a newbie in javascript.I am trying not to hardcode here and thats why i tried to categorise info into arrays and call them out.I used the filter function as i wanted to extract the ‘category’ value and push the sets of question to the user. However, it seemed that my code has failed to read specifically the category part and the debugger kept stating “Cannot read property ‘category’ of undefined”. I hope some kind Samaritan can enlighten me.Thanks!

//CLASSES
class MCQ {

    /* DEFAULT CONSTRUCTOR
        @param questionnum-------------------------------> Question Number
        @param question   -------------------------------> Question
        @param choices    -------------------------------> Choices
        @param answer     -------------------------------> Answers
        @param category   -------------------------------> Category */

        constructor(questionnum, question, choices, correctanswer, category) {
        this.questionnum = questionnum;
        this.question = question;
        this.choices = choices;
        this.cAnswer = parseInt(correctanswer);
        this.category = parseInt(category); 
    }

    /* @return -----------> returns string with questions and options 
       getQuestionSkeleton ----> Gives the structure of the question. */
    getQuestionSkeleton() {
        var result = " ";
        result += "Question " + this.questionnum + ":\n"
        result += this.question + "\n";
        result += this.choices + "\n";

        return result;
    }
}

class Quiz {

    // DEFAULT CONSTRUCTOR FOR 15 QUESTIONS
    constructor() {
        this.questionPool = []; //Declare the question pool property of the quiz class.

    //Populate 4 MCQ and push them into arrays
        //[IT] Category
        this.questionPool.push(new MCQ(1,"What is RAM?", ["(1) Random Access Memory", "(2) A kind of Sheep", "(3) Roughly force something into place", "(4) None of the above"], 1, 1));
        this.questionPool.push(new MCQ(2,"Which Of The Programming Language Is Used To Create Programmes Like Applets.", ["(1) COBOL", "(2) C Language", "(3) Java", "(4) BASIC"], 3, 1));
        this.questionPool.push(new MCQ(3,"Which One Is The First Search Engine In Internet?", ["(1) Google", "(2) Archie", "(3) Altavista", "(4) WAIS"], 2, 1));
        this.questionPool.push(new MCQ(4,"First Computer Virus is known as?", ["(1) Rabbit", "(2) Creeper Virus", "(3) Elk Cloner", "(4) SCA Virus"], 2, 1));

        //[Physics] Category
        this.questionPool.push(new MCQ(1,"A Swimmer Dives Off A Boat. What two factors determine the momentum of the swimmer?", ["(1) Height And Speed", "(2) Mass and Velocity", "(3) Weight and Velocity", "(4)Speed and Mass"], 2, 2));
        this.questionPool.push(new MCQ(2,"During a journey, a car accelerates from 9m/s to 18m/s in 6s.Calculate the acceleration of the car.", ["(1) 1.5m/s^2", "(2) 3.0m/s^2", "(3) 5.0m/s^2", "(4) 10.0m/s^2"], 1, 2));
        this.questionPool.push(new MCQ(3,"Formula written as V(Q/T) is of", ["(1) Acceleration", "(2) Work Done", "(3) Power", "(4) Temperature"], 3, 2));
        this.questionPool.push(new MCQ(4,"Potential Difference of any device can be mesured with instrument known as", ["(1) Voltmeter", "(2) Potentiolmeter", "(3) CRO", "(4) Galvanometer"], 1, 2));

        //[Math] Category
        this.questionPool.push(new MCQ(1,"Differenciate y ln cos(5x)", ["(1) - 5tan(5x)", "(2) 3 cos(5x)", "(3) 5", "(4) 5x (e^2)"], 1, 3));
        this.questionPool.push(new MCQ(2,"Solve The Following pair of Simultaneous equations\n2x + 4y = 16\n3x + 4y = 24", ["(1) x = 0 , y = -8", "(2) x = -8 , y = 0", "(3) x = 0 , y = 8", "(4) x = 8 , y = 0"], 4, 3));
        this.questionPool.push(new MCQ(3,"If log base4 (x) = 12 , then log base2 (x / 4) is equals to ", ["(1) 11", "(2) 48", "(3) -12", "(4) 22"], 3, 3));
        this.questionPool.push(new MCQ(4,"The period of | sin (3x) | is", ["(1) 2pi", "(2) 2pi / 3", "(3) pi / 3", "(4) 3pi"], 3, 3));
    }         
    
    // getNumberOfQuestion --------> Gives the total number of questions in a category
    // Divided by 3 because there are 3 Categories.
    getNumberOfQuestion() {
        return (this.questionPool.length) / 3;
    }    
}

//FUNCTIONS

    //TO SHOW NAVIGATION KEYS 'P' AND 'N'
    //TO STORE USER ANSWER INTO A NEW ARRAY
    function prevNxtStoreFn() {
        var index = 0; //ONLY SURVIVE IN THIS FUNCTION,ONCE OUTSIDE IT DIES.
        var questionAnswerArray = [0, 0, 0, 0]; // STORE ALL QUESTION ANSWER FROM USER {[q1ans, q2ans, q3ans,q4ans]}
        var choice = " "; // NEXT OR PREVIOUS ANS
        var readline = require('readline-sync');

        do {
            var result = " ";

            result += "Question " + (index + 1) + "of "+ getNumberOfQuestion() + ":\n" ;
            result += this.mcqSelected[index].getQuestionSkeleton() + ":\n" ;
            questionAnswer = readline.question(">> ");
            console.log("Your Answer : " + questionAnswer[index]);
            result += "\n (Press N for next question, P for previous question, X to quit the quiz.)";
            console.log(result);
            choice = readline.question(">> ");

            questionAnswerArray.push(questionAnswer); //PUSH THE ANSWER ARRAY INTO questionAnswerArray

            if(choice == "N" || choice == "n") {
                if(index != questionPool.length - 1) {
                    index++;
                }
            }
            else if(choice == "Y" || choice == "y") {
                if(index != 0) {
                    index--;
                }
            }
        }
        while (choice != "X" && choice != "x");
    }

//MAIN EXECUTION CODES
var readline = require('readline-sync');
//DEFAULT CONSTRUCTOR FOR 5 QUESTIONS STORED
//TO PUSH THE 5 QUESTIONS INTO THE ARRAY.
this.mcqSelected = []; //Declare the MCQ selected property of the quiz class.
var name = " ";
var choice = -1;
var menu = " ";

menu += "                                                  Welcome to Quiz Application!                                                 \n";
    do {
        console.log(menu);
        name = readline.question("Fill in your name : ");
        choice = readline.question("Hi " + name + " , please choose the quiz category you would like to attempt: \n (1) IT \n (2) Physics \n (3) Math \n (4) Exit \n >> ");

        if (choice == 1) {
            console.log("\n[IT] Category Selected\n");
            specificQuestions = this.questionPool.category.filter(usercategory);
            this.mcqSelected.push(specificQuestions);
            prevNxtStoreFn();
        }
        else if(choice == 2) {
            console.log("\n[Physics] Category Selected\n");
            specificQuestions = this.questionPool.category.filter(usercategory);
            this.mcqSelected.push(specificQuestions);
            prevNxtStoreFn();
        }
        else if(choice == 3){
            console.log("\n[Math] Category Selected\n");
            specificQuestions = this.questionPool.category.filter(usercategory);
            this.mcqSelected.push(specificQuestions);
            prevNxtStoreFn();
        }
    }
    while (usercategory != "4");

Hi @toodammfilthy, you’re trying to access this.questionPool outside the context of a Quiz object (which you’re not actually instantiating anywhere); so this would just refer to the global object here. Did you mean something like this?

const quiz = new Quiz()
const choice = readline.questionInt('Select category')
const specificQuestions = quiz.questionPool.filter(question => question.category === choice)

BTW I would strongly suggest to use a linter, you’re using a lot of undefined variables in your code that you presumably forgot to declare – see here for instance. And the linter is also telling you that you’re not using the Quiz class anywhere.

<off-topic>
I see the professors have moved on from make and model dropdowns…
</off-topic>

Gonna tag this thread appropriately. Please keep in mind that nodejs does occasionally differ from vanilla JS, and you should tag the thread (or at least mention it’s NodeJS in your post) so that people don’t accidentally give you the wrong advice.

My apologies. Will keep that in mind. Thanks!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.