This is my code, a simple sequel of function were I generate two number, one for the user, one for the PC and who scores the highest number win the game. Firefox has come out with Uncaught SyntaxError: unexpected token: string literal error, I checked my code and everything seems ok to me, I can’t figure out what’s wrong and generates that error
// Generate a random number between 1 and 6 both for user and PC.
// Who does the highest score win.
//I create the random number for user and PC
var userNumber = getRandomNumber(1, 6);
var pcNumber = getRandomNumber(1, 6);
console.log(userNumber);
console.log(pcNumber);
//With highestScore function the winner comes out
var whoWon = highestScore(userNumber, pcNumber);
console.log(whoWon);
//I use this function to obtain the random number
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
//Function highestScore tell who's won the game
//matchMessage tells how the winner or the eventual tie has come
//The return is obviously matchMessage
function highestScore (num1, num2) {
var matchMessage = 'Your number is ' + num1 ', PC number is ' + num2 ', tie!!';
if (num1 > num2) {
matchMessage = 'Your number is ' + num1 ', PC number is ' + num2 ', congrats you've won';
} else if (num1 < num2) {
matchMessage = 'Your number is ' + num1 ', PC number is ' + num2 ', you lost...';
}
return matchMessage;
}
Advertisement
Answer
You are missing a plus
+sign while adding the strings with variables.
What you are doing:
'Your number is ' + num1 ', PC number is '
What it should be:
'Your number is ' + num1 + ', PC number is '
When you are using the same type of quote in a string then you have two ways to correct it:
Use different strings, like:
", congrats you've won"
Or you can escape that string using
, Like', congrats you've won'
Try this:
// Generate a random number between 1 and 6 both for user and PC.
// Who does the highest score win.
//I create the random number for user and PC
var userNumber = getRandomNumber(1, 6);
var pcNumber = getRandomNumber(1, 6);
console.log(userNumber);
console.log(pcNumber);
//With highestScore function the winner comes out
var whoWon = highestScore(userNumber, pcNumber);
console.log(whoWon);
//I use this function to obtain the random number
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
//Function highestScore tell who's won the game
//matchMessage tells how the winner or the eventual tie has come
//The return is obviously matchMessage
function highestScore(num1, num2) {
var matchMessage = 'Your number is ' + num1 + ', PC number is ' + num2 + ', tie!!';
if (num1 > num2) {
matchMessage = 'Your number is ' + num1 + ', PC number is ' + num2 + ', congrats you've won';
} else if (num1 < num2) {
matchMessage = 'Your number is ' + num1 + ', PC number is ' + num2 + ', you lost...';
}
return matchMessage;
}