This page explains the essential JavaScript features used in our Hangman Stage 1 project. You'll learn how JavaScript brings your web page to life, how we structured the game logic, and see side-by-side comparisons of advanced and beginner-friendly code.
JavaScript is a programming language that lets you add interactivity to your web pages. It can respond to user actions, update the page, and control the game logic.
<script src="scripts/hangmanScript1a.js"></script>
We use let and const to create variables. Arrays (like guessedLetters) store lists of values.
const words = ["JAVASCRIPT", "BOOTSTRAP", "PROGRAM", "HANGMAN", "COMPUTER"];
let selectedWord = "";
let guessedLetters = [];
let wrongGuesses = [];
let maxAttempts = 6;
Functions group code into reusable blocks. For example, startGame() sets up a new game.
function startGame() {
// ...setup code...
}
JavaScript can change the HTML on the page using the DOM (Document Object Model). For example:
document.getElementById("gameMessage").textContent = "🎉 You Win!";
This finds the element with id="gameMessage" and changes its text.
We use onclick to run code when a button is clicked:
btn.onclick = () => handleGuess(letter);
btn.onclick = function() {
handleGuess(letter);
};
Both do the same thing! The () => ... is called an "arrow function" and is a shorter way to write functions.
We use for loops to go through arrays or ranges of numbers.
for (let i = 65; i <= 90; i++) {
// Create a button for each letter A-Z
}
let i = 65;
while (i <= 90) {
// Create a button for each letter A-Z
i++;
}
Both loops do the same thing. for loops are more common for counting, but while loops work too.
if statements let the code make choices:
if (selectedWord.includes(letter)) {
guessedLetters.push(letter);
} else {
wrongGuesses.push(letter);
maxAttempts--;
}
Arrays store lists of things (like guessed letters). Methods like .includes() and .join() help you work with arrays.
if (guessedLetters.includes(letter)) { ... }
document.getElementById("wrongGuesses").textContent = wrongGuesses.join(" ");
// Instead of .includes()
let found = false;
for (let i = 0; i < guessedLetters.length; i++) {
if (guessedLetters[i] === letter) {
found = true;
break;
}
}
if (found) { ... }
// Instead of .join(" ")
let wrongText = "";
for (let i = 0; i < wrongGuesses.length; i++) {
wrongText += wrongGuesses[i] + " ";
}
document.getElementById("wrongGuesses").textContent = wrongText.trim();
Modern JavaScript methods like .includes() and .join() make code shorter and easier to read, but you can always use loops if you're more comfortable with them.
The Hangman game uses all these JavaScript features to create an interactive experience. As you learn more, you'll find new ways to write and organize your code!
console.log() messages and experiment with JavaScript live.
Check out the game, AI chatlog, HTML guide, CSS guide, and Bootstrap guide to see how JavaScript works with everything else!