I’m new to JavaScript and working on a rock-paper-scissors game on Codecademy. I’ve run into an error that says ‘unexpected token else’, and I’m not sure why. I’m sure my code should be working, but something’s off. Here is a version of my code:
function generateOption() {
let num = Math.floor(Math.random() * 3);
switch (num) {
case 0:
return 'rock';
case 1:
return 'paper';
case 2:
return 'scissors';
}
}
function compareChoices(playerChoice, computerChoice) {
if (playerChoice === computerChoice) {
return 'It\'s a tie!';
}
if (playerChoice === 'rock') {
if (computerChoice === 'paper') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
// Additional conditions can be added here...
}
console.log(compareChoices('rock', 'scissors'));
I’ve checked for missing brackets and syntax issues but still run into the error. Any ideas on what might be causing this issue?
hey there! i’ve run into this before. check for any misplaced semicolons after your if statements. those can cause unexpected token errors. also, make sure you’re not accidentally using ‘=’ instead of ‘===’ in your comparisons. small things like that can trip you up!
I’ve seen similar issues before, and often the error isn’t in the snippet that you post but in a portion of the code that isn’t immediately apparent. It might be that a misplaced brace or an extra semicolon is disrupting the expected structure of your if-else statements. In my experience, taking a closer look at every block to ensure every opening bracket is properly closed can help. Additionally, isolating sections of the code by temporarily commenting them out might reveal where the problem lies.
I’ve encountered this issue in my own projects before. One thing that often gets overlooked is the consistency of code style. In your case, I noticed you’re using both single and double quotes for strings. While this isn’t causing your current error, it’s a good practice to stick to one style.
As for the ‘unexpected token else’ error, it’s likely occurring in a part of your code that isn’t shown here. Double-check your entire script for any mismatched curly braces or missing semicolons. Also, ensure you’re not accidentally using the assignment operator (=) instead of the comparison operators (== or ===) in your conditional statements.
Another tip from my experience: try using a linter like ESLint. It’s been a lifesaver for me, catching these kinds of syntax errors before they become runtime issues. It might seem like overkill for a small project, but it’s a great habit to develop as you progress in your JavaScript journey.