Node.js
Adding questions
Learn to add questions with the addQuestion method.
The Quiz class and addQuestion
Now we define the Quiz class. This class stores questions in an array. The constructor creates an empty array: this.questions = [];. The addQuestion method adds a new question.
The addQuestion(text, answer) method auto-generates an id: const id = this.questions.length + 1;. Then it builds the object with new Question(id, text, answer) and appends it with this.questions.push(...). This is a builder pattern: each call adds a question and the quiz grows. We take the previous lesson's Question class and add the Quiz class. The quiz becomes a container that manages questions.
The builder pattern
addQuestion is a builder pattern. Each call adds a question to the quiz. Example: quiz.addQuestion("Capital?", "Ankara"); quiz.addQuestion("Largest city?", "Istanbul");. After two calls quiz.questions.length is 2.
The builder pattern is the basic way to construct objects step by step. Instead of giving all data in one constructor, you add each piece with a separate method. This makes the code readable: each addQuestion call defines one question. Also, since the id is auto-generated, the call order determines the id. The first call gets id=1, the second id=2. This keeps the quiz consistent.
Exercise Add the Quiz class and addQuestion method
Take the previous lesson's Question class. Add class Quiz: this.questions = [] in the constructor, addQuestion(text, answer) with const id = this.questions.length + 1; this.questions.push(new Question(id, text, answer));. The last lines are ready: add two questions and print the count.
Show example solution
class Question {
constructor(id, text, answer) {
this.id = id;
this.text = text;
this.answer = answer;
}
}
class Quiz {
constructor() {
this.questions = [];
}
addQuestion(text, answer) {
const id = this.questions.length + 1;
this.questions.push(new Question(id, text, answer));
}
}
const quiz = new Quiz();
quiz.addQuestion("Capital?", "Ankara");
quiz.addQuestion("Largest city?", "Istanbul");
console.log("Question count: " + quiz.questions.length);
Test yourself
-
Complete the addQuestion body
addQuestion(text, answer) {
const id = this.questions.length + 1;
this.questions.____(new Question(id, text, answer));
}
Show answer
addQuestion(text, answer) {
const id = this.questions.length + 1;
this.questions.push(new Question(id, text, answer));
}
-
Match each piece to its role
- this.questions
- Question array
- addQuestion
- Adds a question
- questions.length + 1
- Generates a new id
- new Question
- Creates a question object
-
What happens when quiz.addQuestion is called?
quiz.addQuestion("Soru?", "Cevap")
- The first question is updated
- Quiz silinir
- Yeni soru dizinin sonuna eklenir
- The question count decreases
Show answer
Yeni soru dizinin sonuna eklenir — addQuestion appends a new question to the array.
Next lesson: Running the quiz