When I first started building my Rock, Paper, Scissors game using JavaScript, I was excited to see it come to life in the console. But as soon as I clicked the button to start the game, I was hit with this frustrating error:
Uncaught ReferenceError: game is not defined
If you’re running into this too, you’re not alone. I’ll walk you through why this happens, how I fixed it, and some extra features I added to make the game even more fun.
Understand the Error
Here’s the full error message I got in the browser console:
index.html:14 Uncaught ReferenceError: game is not defined
This told me that the browser couldn’t find the game()
function I was trying to call when I clicked my Play Game button.
Here’s what I had in my HTML:
<button onclick="game()">Play New Game</button>
So why couldn’t it find the function
The Root Cause
Turns out there are two main reasons this can happen:
- The JavaScript file wasn’t loaded properly.
- The
game
function wasn’t in the global scope meaning it couldn’t be accessed from the HTML.
How I Fix It
Check the Script Tag
I made sure my main.js
file was correctly linked after the HTML elements, like this:
<script src="main.js"></script>
Putting this at the bottom of the <body>
ensures all elements are loaded before the script runs.
I also double-checked that the file name matched exactly and that the script file was in the right directory.
Don’t Call game()
Immediately
In my original JavaScript, I had this at the bottom:
game(); // ← this causes the game to start automatically
That’s a problem because it runs as soon as the page loads, even before the user clicks anything. I removed or commented out that line to let the button control when the game starts.
Final Working JavaScript
Here’s my complete, working main.js
after the fix:
let choices = ["rock", "paper", "scissors"];
let winners = [];
function game() {
winners = []; // reset previous results
for (let i = 1; i <= 5; i++) {
playRound(i);
}
document.querySelector("button").textContent = "Play Again";
logWins();
}
function playRound(round) {
const playerSelection = playerChoice();
const computerSelection = computerChoice();
const winner = checkWinner(playerSelection, computerSelection);
winners.push(winner);
logRound(playerSelection, computerSelection, winner, round);
}
function playerChoice() {
let input = prompt("Type Rock, Paper, or Scissors");
while (input == null || !validateInput(input.toLowerCase())) {
input = prompt("Type Rock, Paper or Scissors");
}
return input.toLowerCase();
}
function computerChoice() {
return choices[Math.floor(Math.random() * choices.length)];
}
function validateInput(choice) {
return choices.includes(choice);
}
function checkWinner(choiceP, choiceC) {
if (choiceP === choiceC) {
return "Tie";
} else if (
(choiceP === "rock" && choiceC === "scissors") ||
(choiceP === "paper" && choiceC === "rock") ||
(choiceP === "scissors" && choiceC === "paper")
) {
return "Player";
} else {
return "Computer";
}
}
function logWins() {
const playerWins = winners.filter((w) => w === "Player").length;
const computerWins = winners.filter((w) => w === "Computer").length;
const ties = winners.filter((w) => w === "Tie").length;
console.log("Game Over!");
console.log("Player Wins:", playerWins);
console.log("Computer Wins:", computerWins);
console.log("Ties:", ties);
}
function logRound(player, computer, winner, round) {
console.log(`Round ${round}:`);
console.log("Player chose:", player);
console.log("Computer chose:", computer);
console.log(`${winner} won the round`);
console.log("--------------------------");
}
Now, when I click the button, everything works perfectly no errors
Extra Practice Feature I Added
After fixing the error, I decided to practice more JavaScript and improve the game.
Track Score Across Game
Instead of resetting the score every time, I added persistent totals:
let totalWins = 0;
let totalLosses = 0;
let totalTies = 0;
// After logWins()
totalWins += playerWins;
totalLosses += computerWins;
totalTies += ties;
Show Score on the Page Instead of Console
<div id="scoreboard"></div>
And updated it from JavaScript:
document.getElementById("scoreboard").innerHTML = `
<p>Player: ${playerWins}</p>
<p>Computer: ${computerWins}</p>
<p>Ties: ${ties}</p>
`;
Now I could see the score on the page instead of just the console.
Play Until Someone Wins 3 Times
Instead of playing a fixed five rounds, I made the game loop until someone won 3 times:
let playerScore = 0;
let computerScore = 0;
while (playerScore < 3 && computerScore < 3) {
let player = playerChoice();
let computer = computerChoice();
let winner = checkWinner(player, computer);
if (winner === "Player") playerScore++;
else if (winner === "Computer") computerScore++;
console.log(`Player: ${playerScore}, Computer: ${computerScore}`);
}
Final Thought
Like me, running into errors like "game is not defined"
is just part of learning to code. At first, it was frustrating, but once I understood how the browser loads JavaScript and how function scope affects visibility, the fix became clear. Make sure your script tag comes after the HTML it interacts with, Avoid calling game()
before user interaction, Keep your functions in the global scope if they’re being triggered from HTML.