Get Programming with JavaScript - Listing 3.15
Listing 3.15 - A question and answer for a quiz app
var questionAndAnswer = {
question: "What is the capital of France?",
answer1: "Bordeaux",
answer2: "F",
answer3: "Paris",
answer4: "Brussels",
correctAnswer: "Paris",
marksForQuestion: 2
};
Further Adventures
Listing 3.15 - A question and answer for a quiz app - Task 1
- Use console.log to present the question and answer options in a nicely formatted way.
var questionAndAnswer = {
question: "What is the capital of France?",
answer1: "Bordeaux",
answer2: "F",
answer3: "Paris",
answer4: "Brussels",
correctAnswer: "Paris",
marksForQuestion: 2
};
// Present the question
console.log(questionAndAnswer.question);
// Present the answer options
console.log("A) " + questionAndAnswer.answer1);
console.log("B) " + questionAndAnswer.answer2);
console.log("C) " + questionAndAnswer.answer3);
console.log("D) " + questionAndAnswer.answer4);
Listing 3.15 - A question and answer for a quiz app - Task 1
- Use console.log to present the question and answer options in a nicely formatted way.
Here's an alternative approach.
var questionAndAnswer = {
question: "What is the capital of France?",
answer1: "Bordeaux",
answer2: "F",
answer3: "Paris",
answer4: "Brussels",
correctAnswer: "Paris",
marksForQuestion: 2
};
// Present the question
console.log(questionAndAnswer.question);
// Create a variable for the answer options
var answers = "\n";
// Append the answer options to the answers string
answers += "A) " + questionAndAnswer.answer1 + "\n";
answers += "B) " + questionAndAnswer.answer2 + "\n";
answers += "C) " + questionAndAnswer.answer3 + "\n";
answers += "D) " + questionAndAnswer.answer4 + "\n";
// Display the answer options
console.log(answers);
The escape sequence, \n, is used to specify a new line.
When working with strings, the +=
operator creates a new string by appending the string on its right to the value of the variable on its left. It assigns the new string to the variable.