webdevpuneet.com

Predict the Output Quiz Game — Free HTML CSS JS Snippet

Predict the Output Quiz Game · Games · Plain HTML, CSS & JS · Live preview

CategoryGames
TagsGames

For supporters

Source Code

Want the source code?

Play the game for free. Become a WebDevPuneet supporter to unlock the complete HTML, CSS and JavaScript source code, the exports (HTML, React, Vue, Angular, Tailwind) and Fork.

Play freeSource code: Patreon

Extend with AI

Take This Snippet Further With AI

The AI prompt for this one is for Patreon supporters ($3 a month), along with a site with no ads. Supporters enter the passcode once and it is remembered in this browser.

· Become a supporter

What's included

Features

Eight questions covering genuine JavaScript behaviour: typeof null, default sort, float equality, var closures, + overloading, microtask ordering, const mutation, and object coercion
A written explanation for every question naming the underlying rule and the practical fix
Fifteen-second per-question countdown with a width-animated bar that turns red in the last five seconds
Timeouts routed through the same reveal() function as clicks, so an unanswered question still shows the answer and explanation
Double guard against race conditions between a click and the countdown reaching zero
Shuffled question order via Fisher-Yates over an index array, leaving the source data unmutated
Three-state card (question, explanation, final score) toggled with the hidden attribute rather than innerHTML swaps
Distinct verdict wording for correct, incorrect, and out-of-time outcomes

About this UI Snippet

Predict the Output Quiz Game — Timed Rounds, Shuffled Question Order & An Explanation After Every Answer

Screenshot of the Predict the Output Quiz Game snippet rendered live

"What does this log?" is the single most efficient format for teaching a language's sharp edges, because the learner commits to a prediction before seeing the truth — and a wrong prediction is what makes the explanation stick. This snippet is a complete, playable version of that format for JavaScript: eight questions covering the quirks that actually cost people debugging hours, a per-question countdown, immediate colour-coded reveal, and a written explanation of the mechanism behind every answer.

The questions are real behaviour, not trivia

Each entry covers something a working developer genuinely hits: typeof null returning 'object', [1, 2, 10].sort() producing [1, 10, 2] because the default comparator stringifies, 0.1 + 0.2 === 0.3 being false under IEEE-754, var in a loop with setTimeout logging 3 3 3 because all callbacks share one binding, '5' - 3 and '5' + 3 diverging because + is overloaded, microtasks draining before macrotasks so a resolved promise beats setTimeout(fn, 0), const preventing reassignment but not mutation, and [] + {} coercing to '[object Object]'. Every explain string names the underlying rule and, where useful, the fix — pass a comparator, use let, compare floats with an epsilon.

Shuffled order with a stable answer index

restart() builds a shuffled array of question indices with a Fisher-Yates pass and walks that array rather than the questions themselves, so replaying the quiz presents a different sequence without ever mutating QUESTIONS. The answer for each question is stored as an index into its own options array, which keeps the data compact and makes the reveal logic trivial: mark the button at q.answer correct, and mark the chosen button wrong when it differs.

A countdown that ends the question rather than the game

Each question runs a one-second setInterval driving a width-animated bar that turns red in its last five seconds. Running out of time calls the same reveal() function the click handler uses, passing -1 as the choice — so a timeout is treated as an answered question with no selection: the correct option still highlights, the explanation still appears, and the player still learns the answer. Reusing one reveal path for both routes is what keeps the timeout case from becoming a second, subtly different code path.

Guarding against double scoring

reveal() returns immediately if answered is already true, and every option button is disabled the moment an answer lands. That double guard matters because the timer and a click can otherwise race: a click landing in the same tick as the countdown reaching zero would otherwise run the scoring branch twice. The interval is cleared inside reveal() rather than at the next render, so no stray tick can fire while the explanation is on screen.

Reveal, explanation, and final score as three states

The card shows one of three states at a time — the live question, the explanation panel with the verdict heading and the "Next question" button, or the final score panel — toggled with the hidden attribute rather than by swapping innerHTML. The verdict itself distinguishes three outcomes: correct, wrong, and out of time, so the feedback text always matches how the question actually ended.

Step by step

How to Use

  1. 1
    Read the code blockEach question shows a short, self-contained snippet of real JavaScript in a monospaced panel — the kind of code that appears in a bug report rather than a textbook exercise.
  2. 2
    Answer before the bar runs outA fifteen-second countdown drains a bar across the top, turning red for the final five seconds. Running out of time reveals the answer and its explanation rather than skipping past it, so a timeout still teaches you something.
  3. 3
    Pick one of the four optionsClicking an option immediately locks the question: the correct answer turns green, and a wrong pick turns red alongside it so you can see both what you chose and what was right.
  4. 4
    Read the explanationEvery question carries a written explanation naming the actual rule — the microtask queue draining before macrotasks, the default sort comparator stringifying elements, IEEE-754 rounding — plus the practical fix where one exists.
  5. 5
    Work through all eight questionsThe score counter updates as you go and a final panel shows your total out of eight when the last question is answered.
  6. 6
    Play again for a different orderPlay again reshuffles the question order with a Fisher-Yates pass over an index array, so a replay is not the same sequence — and the QUESTIONS array itself is never mutated.

Real-world uses

Common Use Cases

JavaScript teaching, onboarding, or interview preparation
Predict-the-output is the fastest known format for surfacing misconceptions, because the learner commits before seeing the answer. Pair it with an event loop visualizer so the microtask-ordering question can be followed up with a visual model of why.
Documentation sidebars for language or API gotchas
Any library with surprising behaviour — timezone handling, floating-point money, async ordering — can embed a two-question version of this next to the relevant docs section, turning a warning callout most readers skim into something they engage with.
Developer marketing, conference booths, and careers pages
A quiz that takes two minutes and teaches something real is far better received by a technical audience than a generic lead form, and works well alongside other learn-by-playing snippets like the Regex Match Game.
Reusable timed-quiz engine for any subject
Nothing in the mechanics is JavaScript-specific — swap the QUESTIONS array and the same countdown, reveal, explanation and scoring flow drives a quiz on CSS, SQL, accessibility rules, or internal product knowledge.
Reference for safe timer-and-click race handling
The answered flag plus disabling every option is a compact demonstration of guarding a scoring path that two independent event sources can trigger — the same defence any timed form, auction bid, or countdown checkout needs.
Training and compliance modules with explanations
Because a wrong answer produces an explanation rather than just a red mark, the pattern suits internal training where understanding matters more than the score — security awareness, code review standards, or style-guide quizzes.
Related: Canvas Conway
See the Canvas Conway for a related games pattern worth pairing with this one.

Got questions?

Frequently Asked Questions

The countdown calls the same reveal() function a click does, passing -1 as the chosen index. The question is marked as answered, the correct option highlights, and the explanation appears — you simply score nothing for it. Reusing one reveal path means the timeout case cannot drift into behaving differently from a normal answer.

No. reveal() returns immediately if the answered flag is already set, and all option buttons are disabled the moment an answer lands. The interval is also cleared inside reveal() rather than at the next render, so no stray tick can fire while the explanation panel is showing.

Push an object onto QUESTIONS with four keys: code (the snippet string, with \n for line breaks), options (an array of answer strings), answer (the index of the correct option within that array), and explain (a sentence or two naming the rule and, where useful, the fix). The question count in the header derives from the array length automatically.

No — the snippets are rendered as text into a pre element with textContent, never evaluated. That is deliberate: eval or new Function on quiz content would be both unnecessary and a poor pattern to demonstrate, and the answers are authored rather than computed so the explanations can describe the mechanism rather than just the result.

Yes. Keep QUESTIONS in a module, hold the shuffled order, position, score and answered flag in component state, and render options from data rather than mutating classes. Run the countdown in useEffect / onMounted / ngOnInit keyed on the current question and return a clearInterval cleanup so a question change or unmount cannot leave a timer running — that cleanup is the one thing a naive port usually misses.