Node.js
Quiz model
Design the skeleton of Question and Quiz classes.
Project: Quiz app
In this 5-lesson project you will build a quiz app. First we define the Question class, then grow the Quiz class step by step, and in the last lesson combine it with an Express API.
A Question object has three properties: id (sequence number), text (question text) and answer (correct answer). In JavaScript you define a class with the class keyword. Example: class Question { constructor(id, text, answer) { this.id = id; ... } }. The constructor is called when a new object is created and assigns properties. Each lesson's beginning code includes the previous lesson's solution.
Assigning properties with this
Inside a class this represents the current object. The assignment this.id = id; turns a constructor parameter into an object property. Example: constructor(id, text, answer) { this.id = id; this.text = text; this.answer = answer; }.
After this assignment, an object created with new Question(1, "Capital?", "Ankara") has q.id as 1, q.text as "Capital?", q.answer as "Ankara". Without this, an assigned variable stays a local variable inside the constructor, not a property. So class properties are always assigned with this. This is the fundamental rule of JavaScript classes.
Exercise Define the Question class
Define class Question: constructor(id, text, answer) with body this.id = id; this.text = text; this.answer = answer;. Create an object with const q = new Question(1, "Capital?", "Ankara"). Print with console.log(q.text) and console.log(q.answer).
Show example solution
class Question {
constructor(id, text, answer) {
this.id = id;
this.text = text;
this.answer = answer;
}
}
const q = new Question(1, "Capital?", "Ankara");
console.log(q.text);
console.log(q.answer);
Test yourself
-
When is the constructor called in the Question class?
const q = new Question(1, "Soru?", "Cevap");
- When the class is defined
- When an object is created with new
- When the program starts
- When console.log is called
Show answer
When an object is created with new — The constructor is called when an object is created with new.
-
Complete the constructor body
constructor(id, text, answer) {
this.id = id;
this.text = text;
this.____ = answer;
}
Show answer
constructor(id, text, answer) {
this.id = id;
this.text = text;
this.answer = answer;
}
-
Match each piece to its role
- class
- Defines a class
- constructor
- Initializes a new object
- this
- Represents the current object
- new
- Creates an object
Next lesson: Adding questions