Help with JavaScript Number Guesser Project

so this is my JavaScript number Guesser code so far. I’m trying to link in the computer guess function and the general target functions below, but it doesn’t work. Any suggestions?

let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;
const generateTarget = () => {
Math.floor(Math.random()*10)
};

const computerGuess = () => Math.floor(Math.random()*10)
// Write your code below:
function compareGuesses(computerGuess, humanGuess, targetNumber) {
let computerGuess = computerGuess();
let targetNumber = generateTarget();
if (Math.abs(computerGuess-targetNumber) === Math.abs(humanGuess-targetNumber)){
return true
}else if (Math.abs(computerGuess-targetNumber) < Math.abs(humanGuess-targetNumber)){
return false
}else if (Math.abs(humanGuess-targetNumber) < Math.abs(computerGuess-targetNumber)){
return true
}else{
return ‘Error’
}

Hello, and welcome to the forums!

Take a close look at your two functions that are generating the random numbers:

const generateTarget = () => {
  Math.floor(Math.random() * 10);
};

const computerGuess = () => Math.floor(Math.random() * 10);

An arrow function that doesn’t include the curly braces {} will automatically return the value, so the return keyword isn’t necessary. However, if you include the curly braces, you need to specify what the function should return or JavaScript will use the default undefined

console.log(generateTarget()); // always undefined
console.log(computerGuess());  // random number

I took off the computerGuess line because I found out there was already a chunk of the exact same code working in a different file called game.js. My new code looks like this.
let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;

// Write your code below:
const generateTarget = () => Math.floor(Math.random()*10)
function compareGuesses(computerGuess, humanGuess, targetNumber) {
if (Math.abs(computerGuess-targetNumber) === Math.abs(humanGuess-targetNumber)){
return true
}else if (Math.abs(computerGuess-targetNumber) < Math.abs(humanGuess-targetNumber)){
return false
}else if (Math.abs(humanGuess-targetNumber) < Math.abs(computerGuess-targetNumber)){
return true
}else{
return ‘Error’
}
}

console.log(compareGuesses(computerGuess, 8, generateTarget));

when I tried to pass the functions off as arguements for the compareguesses function it came off as a syntax error. Is there anyway to make the targetNumber function and the computerGuess function linked into the compareGuesses function so the values that these functions give are calculated in the compareGuesses function?

I figured out what happened, Thanks for the help.

3 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.