AI Hints
Home›JavaScript Tutorial›Practice Projects 1
JavaScript · Lesson 115 of 138

Practice: Word Guess

A small game.

⏱ 2 min read▶ Video at 2:18:23🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Time for practice projects. Each one combines several things you've learned. First, a word guessing game. The computer has a secret word, and shows it as blanks. Each guess fills in the matching letters, until the word is complete, or you run out of lives.

Practice: Word Guess
From the video: Practice: Word Guess
  • Practice projects
  • A secret word, as blanks
  • Guess letters, keep your lives

The game

The secret word and a set of guessed letters are the state. Masked shows each letter if it's been guessed, or an_if not. For each guess, we add it to the set, and lose a life if it isn't in the word. We stop when there are no underscores left, or no lives. Here the guesses are written in an array, so we can watch a whole game. Run it.

app.jsjavascript
const secret = "javascript";
const guessed = new Set();
let lives = 3;

const masked = () => [...secret].map(c => guessed.has(c) ? c : "_").join(" ");

for (const letter of ["a", "e", "j", "s", "v", "c", "r", "i", "p", "t"]) {
  guessed.add(letter);
  if (!secret.includes(letter)) lives--;
  console.log(`${letter}: ${masked()}  lives ${lives}`);
  if (!masked().includes("_")) { console.log("You win!"); break; }
  if (lives === 0) { console.log("Game over"); break; }
}
Output
a: _ a _ a _ _ _ _ _ _  lives 3
e: _ a _ a _ _ _ _ _ _  lives 2
j: j a _ a _ _ _ _ _ _  lives 2
s: j a _ a s _ _ _ _ _  lives 2
v: j a v a s _ _ _ _ _  lives 2
c: j a v a s c _ _ _ _  lives 2
r: j a v a s c r _ _ _  lives 2
i: j a v a s c r i _ _  lives 2
p: j a v a s c r i p _  lives 2
t: j a v a s c r i p t  lives 2
You win!

What it used

This small game used a set for the guessed letters, a spread to turn a string into letters, map and join to build the display, template literals, a for of loop, and break. To make it interactive in a browser, you'd swap the array for button clicks, and draw the masked word with text content.

keyvalue
Setguessed letters
[...secret]string to letters
map + jointhe display
breakstop the game

Summary

The word game combined sets, strings, arrays, and loops. Next, checking how strong a password is.

Key takeaways
  • State: secret, guesses, lives
  • masked() display
  • Win or lose
Next up: Practice: Password Checker — rules and scores