Predict the Output Quiz Game — Free HTML CSS JS Snippet

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

Share & Support

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.

Build with AI

Build, Understand, Optimize, and Extend It With AI

Paste this snippet into an AI assistant like Claude and ask it to add a "run it" button that executes each question's code in a sandboxed iframe with a captured console, so players can verify the stated answer themselves rather than taking the explanation on trust — a genuinely instructive extension that also raises real questions about safely executing untrusted code. Other good directions: add difficulty tiers with a scoring multiplier, add a streak bonus that shortens the timer as the player gets hotter, persist a high score and per-question accuracy to localStorage so weak topics can be replayed, or swap the question set for a CSS or TypeScript edition using the same engine.

Prompt to recreate it

Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:

text
Build a timed "predict the output" JavaScript quiz game in plain HTML, CSS, and JavaScript — no frameworks or libraries.

Requirements:
- A QUESTIONS array where each entry has a code string, an options array, the index of the correct option, and an explanation string that names the underlying language rule and the practical fix.
- Use real JavaScript behaviour that developers actually hit — typeof null, the default sort comparator stringifying elements, 0.1 + 0.2 !== 0.3, var closures in a setTimeout loop, + being overloaded for strings, microtasks draining before macrotasks, const preventing reassignment but not mutation, and [] + {} coercion.
- Render the code as text into a pre element with textContent — never evaluate it.
- A per-question countdown driving a width-animated bar that changes colour in its final seconds. When time runs out, call the SAME reveal function a click calls (passing -1 as the choice) so an unanswered question still highlights the correct option and shows its explanation.
- Guard against a click and the countdown both scoring the same question: an answered flag checked at the top of reveal, disabling every option button on reveal, and clearing the interval inside reveal.
- On reveal, mark the correct option green and a wrong choice red simultaneously, and show a verdict that distinguishes correct, incorrect, and out-of-time.
- Shuffle the question order on each play with a Fisher-Yates pass over an array of indices rather than mutating the source array, and show a final score panel with a play-again action after the last question.

Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.

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.

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.