CodeBlanks Logo Icon CodeBlanks

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.

Practice 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).

Starter code

index.js
// Define the Question class
// Assign id, text, answer properties
// Create a question and print it
// write here

Sample solution

index.js
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);

Expected output

Başkent?
Ankara

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is the constructor called in the Question class?

index.js
const q = new Question(1, "Soru?", "Cevap");
  • When the class is defined
  • When an object is created with new Correct answer
  • When the program starts
  • When console.log is called

Explanation: The constructor is called when an object is created with new.

2 Complete the constructor body

Question
constructor(id, text, answer) {
  this.id = id;
  this.text = text;
  this.____ = answer;
}
Answer
constructor(id, text, answer) {
  this.id = id;
  this.text = text;
  this.answer = answer;
}

Explanation: this.answer assigns the answer property.

3 Match each piece to its role

Term Meaning
class Defines a class
constructor Initializes a new object
this Represents the current object
new Creates an object

All lessons in Intermediate