You design a number-guessing game in JavaScript by separating four concerns: a secret value, a finite number of guesses, feedback that narrows the range, and a reset path. The simplest working version needs an input, a button, and about fifteen lines of script. Getting it right means answering design questions first—range, attempt limit, feedback style, input validation—then coding the state machine that enforces them. This guide walks through that process in order, from a paper design to a playable browser game, with the reasoning behind each choice and the failure modes that trip up beginners.

The example throughout is a classic "guess a number between 1 and 100 in ten tries" game, because that constraint set is easy to verify by hand and generalizes to word games, higher/lower card games, and dice variants.

Design first: decide the rules before writing a line

Most broken guess games fail at the design stage, not the syntax stage. A guess game is a small state machine, and the rules determine its shape. Write these answers down before coding:

What is the secret space? A uniform integer from 1 to 100 is the standard. Any bounded set works—letters, a shuffled list of words, a random card. The size of the space determines how many guesses are fair.

How many attempts? This is a math question, not a taste question. Each guess ideally splits the remaining space roughly in half. From a range of 100, ten guesses is generous: binary search needs about log₂(100) ≈ 6.64, so 7 guesses always suffice with perfect play. Ten gives casual players slack. If you set the limit below 7, a player using optimal strategy can still lose, which feels unfair in a luck-flavored game. A common beginner mistake is choosing three attempts for a range of 100—that's effectively unwinnable by reasoning.

What feedback does each guess produce? The minimal contract is "too high," "too low," or "correct." Stronger feedback narrows the displayed range after each guess, which reduces frustration and makes the game self-teaching. A harsher variant offers only "warm/cold" distance hints; that's a different game with different psychology, and it's harder to balance.

Does a wrong guess cost anything beyond the attempt? Pure attempt limits are cleanest. Adding score penalties or time pressure complicates tuning, and you can layer those on after the core loop works.

What happens on win and loss? The secret must be revealed either way, with a clear reset control. A game that ends in a dead state with no restart path is a common bug.

Write the ruleset as three sentences, for example: "The computer picks a whole number from 1 to 100. You get ten guesses. After each guess you're told higher or lower, and the valid range shrinks." If your three sentences are ambiguous, the code will be too.

Build the state model and transitions

Every guess game has four or five pieces of state. Naming them explicitly prevents the classic bugs where the secret is regenerated mid-game or the attempt counter drifts.

secret: the hidden target, fixed at game start. attemptsLeft: remaining guesses, decremented once per valid guess. low and high: the currently possible range, updated from feedback. status: one of playing, won, or lost.

The transitions are small enough to enumerate. A valid guess either equals the secret (status becomes won), or it doesn't (decrement attempts; update the range; if attempts hit zero, status becomes lost). Anything else—empty input, non-numeric text, out-of-range numbers—is not a guess at all and must not consume an attempt. That distinction is where most beginner implementations leak.

Two design decisions fall out of the state model. First, the secret must be generated exactly once in the start function, never inside the guess handler; otherwise a player who guesses wrong will silently be guessing against a moving target. Second, attempt decrement belongs in one place, so the counter can't be double-decremented by a stray event listener.

Set up the HTML and CSS shell

The page needs an input, a submit button, a message area, an attempts counter, and a reset button. Give each a unique id so the script can find it. Keep the markup minimal; styling is cosmetic and can wait until the logic works.

Two accessibility details matter more than they look. The aria-live="polite" attribute makes screen readers announce each feedback message, which is the whole game for a blind player. The inputmode="numeric" attribute summons a number pad on phones. Neither replaces a real , which you should add in production; the visible instructions above the input are fine for a demo but a proper is the standard.

The CSS can be ten lines—a centered column, a readable font, a monospace range display. Don't spend an hour on gradients before the game is playable.

Code the core loop step by step

The script has four jobs: generate the secret, read and validate input, compare, and end or continue. Write them as named functions so each is testable in isolation.

Step 1: Define the constants and state. Put the range bounds and attempt limit at the top so tuning is one edit.

Step 2: Generate a random integer in an inclusive range. Math.random() returns a float from 0 inclusive to 1 exclusive, so scaling and flooring must respect the offset.

The + 1 is not optional. Omitting it makes the top value unreachable; omitting the min offset shifts the whole range. This is the single most common off-by-one in beginner guess games, and it's silent—nobody notices that 100 is never the answer. Modern browsers also support crypto.getRandomValues for stronger randomness, but for a guessing game Math.random() is honest about being unpredictable enough; use crypto only if you later turn the secret into something security-relevant, which a local training game never is.

Step 3: Write the start function. It resets every piece of state and every visible element.

Calling startGame() once on load and again on reset means there is a single code path that establishes a valid game. Any state that isn't reset here is a bug waiting to happen.

Step 4: Validate the guess. A guess is valid only if it parses as an integer within the current known bounds. Rejecting values outside low..high is a design choice—it's technically valid data, but accepting it lets a player brute-force with numbers that the feedback has already ruled out. Most implementations reject them and say "that's outside the possible range," which is friendlier than silently wasting a turn.

Number.isInteger rejects "3.5", "abc", and "" cleanly. Beware parseInt("12abc") returning 12—that's lenient parsing you do not want here, because it hides typos.

Step 5: Compare, respond, and transition. This is the heart of the game.

Note the range update: after a guess of 42 that's too low, the new low bound is 43, not 42, because 42 is proven wrong. Also note that the "new game" button clears the message and the "out of tries" message overwrites the last feedback—otherwise a player sees "Too high" and "Out of tries" fighting for the same space.

Step 6: Wire the events and disable input when the game is over.

The Enter-key handler is not optional politeness; typing a number and pressing Enter is the natural gesture, and a game that ignores it feels broken. Guard the handler with the status !== "playing" check so a stray Enter after the game ends can't fire a comparison against stale state.

What success looks like and how to verify it

A working build passes these checks by hand, in order:

1: Load the page and confirm the secret is not shown anywhere in the UI or obvious in the console. (For debugging, temporarily log it; remove the log before shipping.) 2: Guess the midpoint, 50. You see either "Too high" or "Too low," and the displayed range tightens to 1–49 or 51–100 accordingly. 3: Enter 0, 101, abc, 3.5, and an empty string. Each is rejected with a message and none of them costs a try. 4: Guess the secret. You see "Correct," the input disables, and the attempt count is right. 5: Start a new game and confirm attempts reset to 10 and the range resets to 1–100. 6: Use ten wrong guesses and confirm the loss message names the secret and the input disables.

To check the randomness, temporarily change the range to 1–3 and play twenty rounds; every value should appear. Better, run the generator in isolation: for (let i = 0; i < 10000; i++) { const v = randomInt(1, 100); if (v < 1 || v > 100) throw new Error(v); }. That catches bounds errors but not distribution bias; for distribution, tally ten thousand outputs and eyeball that each of 1–100 lands near 100 times.

A good sanity check for the attempt economy: because binary search needs 7 guesses for a range of 100, ten attempts should let a careful player win almost every time. If you watch someone play and they run out of tries while playing sensibly, your limit is too tight.

Handling the edge cases that break beginner games

Repeated guesses. If the player guesses 50, sees "Too low," and guesses 50 again, most implementations consume a second attempt and produce the same feedback. That's technically fair but feels punitive and wastes the range logic, since the range update already excludes 50. Two reasonable fixes: reject out-of-range repeats like any other out-of-range value (the guess < low || guess > high check already does this once the bound moves past 50), or track guesses in a Set and refuse duplicates with a message. The range check is simpler and falls out naturally—after a "too low" on 50, 50 is below low, so it's rejected without costing a try. When the guess equals a bound exactly, the range rule catches it once the bound has advanced to 51.

The floating-point input. type="number" still lets users type 3.5 or 1e2. Number.isInteger filters these. Be aware that 1e2 parses as 100, which is legitimate—reject only non-integers, not scientific notation, unless you want strict decimal typing.

Stale state after reset. If the reset button shares a listener that captures variables by value rather than reading module-scope state, reset can leave the old secret live. The structure above avoids this by keeping secret in a shared scope that startGame overwrites.

Rapid clicking. Two clicks in a fast double-click can fire handleGuess twice before the input clears. The guard if (status !== "playing") return prevents play after the game ends, but mid-game double-fires are harmless because the second read finds an empty input and is rejected by parseGuess. Clearing the input synchronously at the end of the handler closes most of the window.

Number input quirks. Some browsers keep the old value in input.value when the user types invalid characters, and type="number" on some mobile browsers returns "" for intermediate states. Reading input.value as a string and parsing yourself, as parseGuess does, is more predictable than trusting valueAsNumber, which yields NaN in more places than people expect.

Scale it up: hints, difficulty, and variants

Once the core loop is solid, the same state model extends cheaply. Each addition below is a plugin onto the four-function skeleton, not a rewrite.

Range display with narrowing. Already included: the "possible range" line updates on every guess. This transforms the game from a pure guessing game into a transparent search, which many players enjoy more. If you want the classic opaque feel, drop the range line and keep only "higher/lower."

Hint modes. After five failed guesses, offer a hint such as "the number is even" or "the digit sum is 9." Implement as a function that inspects secret and returns a string; gate it behind attemptsLeft <= MAX_ATTEMPTS / 2. This changes the win rate, so re-tune the attempt limit if the hint is generous.

Difficulty levels. Tie a difficulty selector to two numbers: the range size and the attempt count. Easy: 1–50, ten tries. Medium: 1–100, eight tries. Hard: 1–1000, ten tries (log₂(1000) ≈ 9.97, so ten is barely feasible; use twelve for accessibility). The logic is identical; only the constants change, so store them in a config object rather than scattering literals.

Scoring. Award points per win: max(0, attemptsLeft) * 10 rewards efficiency and keeps the score arithmetic visible and reproducible. A typical run winning with 3 tries left scores 30; a last-guess win scores 10. Avoid multiplicative bonuses that scale unpredictably with difficulty unless you have a balance table to check against.

Word and card variants. The secret becomes an element from an array, feedback becomes "earlier in the alphabet" or "higher card," and validation checks membership in an allowed set instead of an integer range. The attempt limit should scale with the set size—for 26 letters, five guesses matches log₂(26) ≈ 4.7. The comparison logic changes from < and > to index-in-array or a comparator function, but the surrounding flow, attempt bookkeeping, and end-state handling are unchanged.

A "warmer/colder" variant. Instead of telling the player higher or lower, give distance-only feedback ("warmer than your last guess") but no directional cue. That game is much harder—there's no guaranteed strategy and the attempt limit needs to be far more generous—so test it with yourself before shipping. Most players find pure distance feedback without direction frustrating within a few rounds.

Undo and guess history. Store each guess with its feedback in an array and render a list. This helps players spot patterns and makes the narrowing range visible in retrospect. It also makes debugging easy and is a natural place to add persistence with localStorage if you want the game to survive a refresh.

Testing the logic outside the browser

The comparison and range-updating logic are pure enough to test without a DOM. Extract parseGuess and a comparison helper into a small module, or duplicate them in a test file, and check the properties that matter:

After a "too low" response to a middle guess, the new low equals guess + 1 and the new range never includes the guessed number. An out-of-range guess returns without changing attemptsLeft. A correct guess always transitions to won regardless of attempts remaining. Ten consecutive wrong guesses consume exactly ten attempts. The generator produces only integers within inclusive bounds across many draws.

You don't need a test framework for a game this small; a console.assert suite run once per change catches nearly everything. The point is that "it looks right in the browser" is a weak check, because the interesting cases—the tenth attempt, the boundary value, the duplicate guess—are tedious to trigger by hand and trivial to test in code.

Ship it and know when to stop digging

The completed game is a few dozen lines of HTML, CSS, and JavaScript—small enough to read top to bottom, which is the right size for a learning project. Ship it once the six-step verification list passes and one other person can play it without instructions. The temptation at that point is to add accounts, leaderboards, and animations; resist until you've written the version down and used it. A guess game is a tutorial in state management, input validation, and honest arithmetic, and the fastest way to learn those lessons is to finish the small version and immediately build a second one with a different rule—letters, cards, or a shrinking range—reusing the architecture. The pattern of "fixed secret, decremented resource, monotonic narrowing, single reset path" carries over to almost any interactive game you'll build next.