JavaScript
Defining question objects
Build an array of objects holding question, options and correct answer.
The question object
We'll define each question as an object. An object keeps related data in curly braces as key-value pairs:
{ question: "...", options: [...], answer: 1 }
Here question is the text shown to the user, options is the array of choices, and answer is the index of the correct option. One object packages every part of a question, so the data stays organized.
An array of question objects
A single question object isn't enough; we collect many questions in an array. Each element is an object:
const questions = [{ ... }, { ... }];
This structure is called an array of objects. questions[0] gives the first question, questions[1] the second. questions.length tells us how many questions there are. With for...of we can walk through all of them.
Exercise Define an array of question objects
In the previous step you declared an empty questions array. Now add at least two question objects to it. Each object should have question, options and answer properties. Then print the number of questions with console.log(questions.length).
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 }
];
console.log(questions.length);
Test yourself
-
Complete the correct answer index
const firstQuestion = {
question: "Capital of Turkey?",
options: ["İzmir", "Ankara", "Bursa"],
answer: ____
};
console.log(firstQuestion.answer);
Show answer
const firstQuestion = {
question: "Capital of Turkey?",
options: ["İzmir", "Ankara", "Bursa"],
answer: 1
};
console.log(firstQuestion.answer);
-
In const questions = [{ q: 'A', answer: 1 }, { q: 'B', answer: 0 }]; what does questions[1].answer return?
Show answer
0 — Correct! questions[1] is the second object and its answer property is 0.
-
Match the expression to its value
- questions[0].question
- Capital of Turkey?
- questions[0].options[1]
- Ankara
- questions[0].answer
- 1
- questions.length
- 2
Next lesson: Showing questions and getting answers