CodeBlanks Logo Icon CodeBlanks

Showing questions and getting answers

JavaScript course · Beginner · Lesson 79/133

Show questions one by one with for...of and collect answers.

Walking through questions with for...of

To go through the question array in order, we use a for...of loop. It gives us one element of the array at each step:

for (const q of questions) { ... }

Here q is one question object per step. Inside the loop body we reach that question's data with q.question, q.options and q.answer. for...of hides indexes and gives values directly.

Turning answers into numbers

We'll keep the user's answers in a userAnswers array. Each answer is stored as the option number in string form: "1", "0" and so on.

To turn such a string into a number we use parseInt. For example parseInt(userAnswers[0]) converts the string "1" into the number 1. Then we can use it as an index like q.options[userAnswer] to read the option's text.

Exercise Show the questions and read answers

Below the questions array you defined, add a userAnswers array (each answer is a string like "1", "0"). Then set up an answerIndex counter and a for...of loop: for each question, convert the answer with parseInt(userAnswers[answerIndex]), print the question text with console.log(q.question), and print the chosen option with console.log("Your answer:", q.options[userAnswer]). Increment answerIndex at the end.

Show example solution
// Define the quiz questions
const questions = [
  { question: "Capital of Turkey?", options: ["İzmir", "Ankara", "Bursa"], answer: 1 },
  { question: "Wettest city?", options: ["Rize", "Konya", "Ankara"], answer: 0 }
];
// User answers (option indexes as strings)
const userAnswers = ["1", "0"];
let answerIndex = 0;
for (const q of questions) {
  const userAnswer = parseInt(userAnswers[answerIndex]);
  console.log(q.question);
  console.log("Your answer:", q.options[userAnswer]);
  answerIndex++;
}

Test yourself

  1. In for (const q of questions) { ... }, what is q at each step?

    • The index of the question (0, 1, 2, ...)
    • The options array of the question
    • The question object itself
    • The value of the correct answer
    Show answer

    The question object itself — Correct! for...of yields the element; here each element is a question object.

  2. Complete the parseInt call

    const userAnswer = parseInt(____);
    Show answer
    const userAnswer = parseInt(userAnswers[answerIndex]);
  3. Match the expression to its meaning

    for (const q of questions)
    Walks each question in turn
    parseInt(userAnswers[0])
    Converts "1" string into the number 1
    q.options[userAnswer]
    Text of the chosen option
    q.question
    Question text

All lessons in Beginner