Node.js
Running the quiz
Learn to ask questions in turn with the run method.
Running the quiz with run
Now we add a run method to the Quiz class. This method prints questions in order. Example: run() { for (let i = 0; i < this.questions.length; i++) { console.log(this.questions[i].text); } }.
The for loop walks the questions array from start to end. this.questions[i] gives each question; .id and .text access its properties. The output looks like: Question 1: Capital?, Question 2: Largest city?. This is the core function of a quiz: showing questions to the user. In a real app you would collect an answer after each question; here we just print. We take the previous lesson's solution and add the run method.
Walking with a for loop
for (let i = 0; i < this.questions.length; i++) walks an array from start to end. i starts at zero and increases up to length. You access each item with this.questions[i].
This is the basic way to traverse an array in JavaScript. The condition i < length stops at the end. i++ increments by one each step. Inside the loop body, this.questions[i].id and this.questions[i].text access each question's properties. The output: Question 1: Capital?, Question 2: Largest city?. This pattern is used to show questions in a table, list them or process them in order.
Exercise Add the run method
Take the previous lesson's solution. Add a run() method to the Quiz class: for (let i = 0; i < this.questions.length; i++) { console.log("Question " + this.questions[i].id + ": " + this.questions[i].text); }. The last line is ready: quiz.run();
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));
}
run() {
for (let i = 0; i < this.questions.length; i++) {
console.log("Question " + this.questions[i].id + ": " + this.questions[i].text);
}
}
}
const quiz = new Quiz();
quiz.addQuestion("Capital?", "Ankara");
quiz.addQuestion("Largest city?", "Istanbul");
quiz.run();
Test yourself
-
Match each piece to its role
- run()
- Prints questions
- for loop
- Walks questions in order
- this.questions[i]
- Gives one question
- .text
- Question text
-
Complete the for loop condition
for (let i = 0; i < this.questions.____; i++) { console.log(i); }
Show answer
for (let i = 0; i < this.questions.length; i++) { console.log(i); }
-
What does this.questions[i] give?
this.questions[i]
- The array's length
- All questions
- The number of questions
- Tek bir soruyu
Show answer
Tek bir soruyu — questions[i] gives the i-th item (one question).
Next lesson: Score calculation