SyntaxPilot
Courses/JavaScript/Lesson 15

JavaScript · Lesson 15 of 40 · 9 min

Basics project: a quiz game

queued

These are the notes for JavaScript episode 15, the first project of the course. You will build a quiz game that reads the player's answers from input, scores them, gives a grade and reviews the mistakes. On the way you'll see why copy-pasted code breaks, turn the questions into data (an array of objects), write one function and one loop instead of repeated code, clean messy input, fix TypeError: Cannot read properties of undefined (reading 'trim') with a safe default, validate answers with throw and try/catch, and build a report card with map and filter. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js): type the answers, one per line, into the input box before you press Run.

What this project uses: template literals (episode 4), if/else (5), loops (6), arrays (7), objects (8), functions and arrow functions (9), map/filter/reduce (11), destructuring and spread (12), throw and try/catch (13), reading stdin (14).

The real-life idea: one answer key

A teacher checks 40 answer sheets for the same 20 questions. She doesn't invent a new way of checking for every question: she writes one answer key (the questions and right answers, once) and uses one method (compare, tick, count) for every sheet. Our first attempt does the opposite.

Attempt 1: the copy-paste quiz

const input = require("fs").readFileSync(0, "utf8").trim().split("\n");
let score = 0;
console.log("Q1. Capital of India?  A) Mumbai  B) Delhi  C) Pune");
if (input[0] === "B") score++;
console.log("Q2. 2 + 2 * 2 = ?  A) 6  B) 8  C) 4");
if (input[1] === "A") score++;
console.log("Q3. Chai is made from?  A) Coffee beans  B) Rice  C) Tea leaves");
if (input[1] === "C") score++;
console.log(`Score: ${score}/3`);

Input: B, A, C (all correct).

Q1. Capital of India?  A) Mumbai  B) Delhi  C) Pune
Q2. 2 + 2 * 2 = ?  A) 6  B) 8  C) 4
Q3. Chai is made from?  A) Coffee beans  B) Rice  C) Tea leaves
Score: 2/3

A perfect paper scored 2/3. Line 8 was copied from line 6 and still checks input[1], the answer to question 2.

Why it failed: the same logic is pasted once per question, and the questions are mixed into the code. 50 questions means 150 lines that must all be edited perfectly, and one slip silently costs a student marks. (Also: 2 + 2 * 2 is 6 because * runs before +, episode 3.)

Attempt 2: questions as data, one function, one loop

const questions = [
  { q: "Capital of India?", options: ["Mumbai", "Delhi", "Pune"], answer: "B" },
  { q: "2 + 2 * 2 = ?", options: ["6", "8", "4"], answer: "A" },
  { q: "Chai is made from?", options: ["Coffee beans", "Rice", "Tea leaves"], answer: "C" },
  { q: "typeof \"42\" is?", options: ["number", "string", "NaN"], answer: "B" },
];
const answers = require("fs").readFileSync(0, "utf8").trim().split("\n");
const LETTERS = ["A", "B", "C"];
function ask({ q, options }, number) {
  const choices = options.map((opt, i) => `${LETTERS[i]}) ${opt}`);
  console.log(`Q${number}. ${q}  ${choices.join("  ")}`);
}
let score = 0;
questions.forEach((question, i) => {
  ask(question, i + 1);
  if (answers[i] === question.answer) score++;
});
console.log(`Score: ${score}/${questions.length}`);

Input: B, A, C, B.

Q1. Capital of India?  A) Mumbai  B) Delhi  C) Pune
Q2. 2 + 2 * 2 = ?  A) 6  B) 8  C) 4
Q3. Chai is made from?  A) Coffee beans  B) Rice  C) Tea leaves
Q4. typeof "42" is?  A) number  B) string  C) NaN
Score: 4/4
  • Each question is an object: q (the text), options (an array), answer (the right letter). The array of them is our answer key.
  • ask destructures the question (episode 12) and uses map with the index to turn ["Mumbai", "Delhi", "Pune"] into ["A) Mumbai", "B) Delhi", "C) Pune"], then join(" ").
  • forEach gives each question and its index i, so answers[i] is the matching answer. There is one comparison line, used for every question.
  • questions.length instead of a hard-coded 3.
  • In the video, the fourth question was added with one line of data and no new logic. That's the payoff of keeping data separate from logic.

Messy answers

Small letters and spaces

Input: b, A (with a space), C, B. With the code above:

Score: 2/4

"b" === "B" is false, and so is "A " === "A". Comparisons are exact. Clean the answer first:

  const given = answers[i].trim().toUpperCase();
  if (given === question.answer) score++;
Score: 4/4

Fewer answers than questions

Input: only B and A.

Q1. Capital of India?  A) Mumbai  B) Delhi  C) Pune
Q2. 2 + 2 * 2 = ?  A) 6  B) 8  C) 4
Q3. Chai is made from?  A) Coffee beans  B) Rice  C) Tea leaves
.../main.js:16
  const given = answers[i].trim().toUpperCase();
                           ^

TypeError: Cannot read properties of undefined (reading 'trim')

There's no third answer, so answers[2] is undefined, and undefined has no trim. The game crashes before printing a score. Give it a safe default with || (logical OR returns the right side when the left side is falsy, such as undefined or ""):

  const given = (answers[i] || "").trim().toUpperCase();
Q1. Capital of India?  A) Mumbai  B) Delhi  C) Pune
Q2. 2 + 2 * 2 = ?  A) 6  B) 8  C) 4
Q3. Chai is made from?  A) Coffee beans  B) Rice  C) Tea leaves
Q4. typeof "42" is?  A) number  B) string  C) NaN
Score: 2/4

The final version: validation and a report card

const questions = [
  { q: "Capital of India?", options: ["Mumbai", "Delhi", "Pune"], answer: "B" },
  { q: "2 + 2 * 2 = ?", options: ["6", "8", "4"], answer: "A" },
  { q: "Chai is made from?", options: ["Coffee beans", "Rice", "Tea leaves"], answer: "C" },
  { q: "typeof \"42\" is?", options: ["number", "string", "NaN"], answer: "B" },
];
const LETTERS = ["A", "B", "C"];
function readAnswer(text, options) {
  const given = (text || "").trim().toUpperCase();
  if (given === "") throw new Error("no answer");
  if (!LETTERS.slice(0, options.length).includes(given)) throw new Error(`"${given}" is not an option`);
  return given;
}
const answers = require("fs").readFileSync(0, "utf8").trim().split("\n");
const results = questions.map((question, i) => {
  try {
    const given = readAnswer(answers[i], question.options);
    return { ...question, given, correct: given === question.answer };
  } catch (err) {
    return { ...question, given: err.message, correct: false };
  }
});
const score = results.filter((r) => r.correct).length;
const percent = Math.round((score / questions.length) * 100);
let grade;
if (percent >= 75) grade = "Quiz master!";
else if (percent >= 50) grade = "Good, keep going";
else grade = "Revise and try again";
console.log(`Score: ${score}/${questions.length} (${percent}%) ${grade}`);
for (const r of results.filter((r) => !r.correct)) {
  console.log(`  ${r.q} you: ${r.given}, answer: ${r.answer}`);
}

Input: b, A, E (and nothing for question 4).

Score: 2/4 (50%) Good, keep going
  Chai is made from? you: "E" is not an option, answer: C
  typeof "42" is? you: no answer, answer: B

How it works:

  • readAnswer cleans the text and throws when it's empty or not a valid letter. LETTERS.slice(0, options.length) is the list of letters this question allows; includes checks membership.
  • map turns every question into a result object: the question spread in (...question), plus given and correct. If readAnswer threw, catch stores the reason in given and marks it wrong. Nothing crashes.
  • filter((r) => r.correct).length is the score; Math.round rounds the percentage.
  • An if / else if / else chain picks the remark.
  • A second filter lists only the wrong answers, with the right letter.

Level up: points per question and four options

Hard questions should be worth more. Because the questions are data, that's one new field, points; four options means one more letter in LETTERS and one more option per question. ask wouldn't change at all.

const questions = [
  { q: "Capital of India?", options: ["Mumbai", "Delhi", "Pune", "Chennai"], answer: "B", points: 1 },
  { q: "2 + 2 * 2 = ?", options: ["6", "8", "4", "10"], answer: "A", points: 2 },
  { q: "typeof \"42\" is?", options: ["number", "string", "NaN", "object"], answer: "B", points: 3 },
];
const LETTERS = ["A", "B", "C", "D"];
const answers = require("fs").readFileSync(0, "utf8").trim().split("\n");
const results = questions.map((question, i) => {
  const given = (answers[i] || "").trim().toUpperCase();
  return { ...question, given, correct: given === question.answer };
});
const earned = results.reduce((sum, r) => (r.correct ? sum + r.points : sum), 0);
const possible = questions.reduce((sum, q) => sum + q.points, 0);
console.log(`Points: ${earned}/${possible}`);

Input B, C, b:

Points: 4/6
  • reduce (episode 11) starts at 0 and adds a question's points only when it's correct.
  • A second reduce adds up all the points for the maximum.
  • A new rule took one field of data and two lines of logic.

Common mistakes (and what really happens)

You wrote What happens Why Fix
a pasted if (input[1] === "C") (no error) 2/3 for a perfect paper one index not changed after copy-paste questions as data + one loop
answers[i] === "B" when the player typed b (no error) marked wrong === is exact .trim().toUpperCase()
answers[i].trim() with too few answers TypeError: Cannot read properties of undefined (reading 'trim') answers[i] is undefined (answers[i] \|\| "").trim()
`Score: ${score}/3` (no error) wrong after adding a question hard-coded count questions.length
E counted wrong silently (no error) no explanation no validation throw new Error(...), then catch
split("\n") without trim() (no error) an extra empty answer the last Enter (episode 14) trim().split("\n")

Practice

  1. Add five questions of your own (data only: the logic must not change).
  2. Print the points as a percentage, with a grade.
  3. Give each question a category and print the score per category.
Solutions and hints
  1. Just add objects to the questions array.
  2. Math.round((earned / possible) * 100), then the same if / else if / else chain as the final version.
  3. Count right and total answers per category in an object:
const questions = [
  { q: "Capital of India?", answer: "B", category: "GK" },
  { q: "2 + 2 * 2 = ?", answer: "A", category: "Maths" },
  { q: "10 / 4 = ?", answer: "C", category: "Maths" },
  { q: "Chai is made from?", answer: "C", category: "GK" },
];
const answers = require("fs").readFileSync(0, "utf8").trim().split("\n");
const byCategory = {};
questions.forEach((question, i) => {
  const given = (answers[i] || "").trim().toUpperCase();
  const c = question.category;
  if (!byCategory[c]) byCategory[c] = { right: 0, total: 0 };
  byCategory[c].total++;
  if (given === question.answer) byCategory[c].right++;
});
for (const [category, { right, total }] of Object.entries(byCategory)) {
  console.log(`${category}: ${right}/${total}`);
}

Input B, A, B, c:

GK: 2/2
Maths: 1/2

Object.entries turns the object into [key, value] pairs, and destructuring unpacks each one (the options are left out to keep the example short).

Quick quiz

What does this print?

const answers = ["b", " c "];
const clean = [0, 1, 2].map((i) => (answers[i] || "").trim().toUpperCase());
console.log(clean);
  • A. [ 'B', 'C', '' ]
  • B. [ 'b', 'c', '' ]
  • C. TypeError
  • D. [ 'B', 'C', undefined ]
Answer

A. answers[2] is undefined, so || gives "", which trims safely. The other two are trimmed and uppercased.

Interview questions

  • Why is copy-pasted code risky? What does "separate data from logic" mean?
  • How would you store quiz questions in JavaScript?
  • What does forEach((item, i) => ...) give you that for...of doesn't (directly)?
  • How do you make a comparison case-insensitive and ignore extra spaces?
  • What does x || "" do when x is undefined? When is || a bad default? (Hint: 0.)
  • Why build an array of result objects instead of only counting the score?
  • How would you add points per question?

Glossary

Term Meaning Example
Project a complete program that combines many concepts this quiz game
Copy-paste code the same logic repeated with small edits; bugs get copied too one if per question
Data-driven behaviour comes from data, not from repeated code the questions array
Array of objects a list where each item has named fields [{ q, options, answer }, ...]
Answer key the questions and their right answers, stored once answer: "B"
Normalise (clean) input make input consistent before comparing .trim().toUpperCase()
toUpperCase() returns the string in capital letters "b".toUpperCase() → "B"
includes(x) true if the array contains x ["A", "B"].includes("B")
slice(start, end) a copy of part of an array LETTERS.slice(0, 3)
Default with \|\| use the right side when the left is falsy answers[i] \|\| ""
Falsy values treated as false: undefined, null, "", 0, NaN, false "" \|\| "x" → "x"
Validation checking a value against the rules, with a reason when it fails readAnswer throws
Result object a record of what happened for one item { ...question, given, correct }
Math.round rounds to the nearest whole number Math.round(66.7) → 67
Report card a summary: score, percentage, grade, mistakes the final output

Summary

  • Copy-pasted logic copies bugs. Store the questions as data and write the logic once.
  • One ask function and one loop handle any number of questions; a new question is one line of data.
  • Clean input (trim, toUpperCase), give missing values a safe default (|| ""), and validate with throw + try/catch.
  • map builds result objects; filter gives the score and the review; if/else picks the grade; reduce totals points.

Next episode: classes and objects. Our questions were plain objects typed by hand; a class is a blueprint that builds similar objects for you.