Number Guesser

The code wouldn’t work. When calling the function, it would return undefined. Do I need to call other functions to make this work? Am I passing the wrong parameters?

The link to the practice: https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-javascript-syntax-part-i/modules/fecp-challenge-project-number-guesser/projects/number-guesser-independent-practice

let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;

// Write your code below:
const generateTarget = () => {
  Math.floor(Math.random() * 10);
}

const compareGuesses = (humanGuess, computerGuess, targetGuess) => {
  if (Math.abs((targetGuess - humanGuess)) >= (Math.abs(targetGuess - computerGuess))) {
    return true;
  }
  else {
    return false;
  }
}

const updateScore = (winner) => {
  if (winner === 'human') {
    humanScore += 1;
  }
  else if (winner === 'computer') {
    computerScore += 1;
  }
}

const advanceRound = () => {
  currentRoundNumber += 1;
}

compareGuesses(humanGuess, computerGuess, targetGuess);

This function returns undefined. Can you see why?

Hint

Forgot to return the number. Overlooked that. It works now. Many thanks!

1 Like

You’re welcome. The subtle syntax differences between arrow functions and concise body arrow functions can be confusing.

Yeah, thanks again! By the way, there is one thing I still don’t understand about how the code works. For #5, the score variable (‘humanScore’ or ‘computerScore’) would increase by 1 depending on the winner passed in to ‘updateScore’. The string passed will be either ‘human’ or ‘computer’, but how does passing the strings work? Although I added the strings, ‘human’ and ‘computer’ to determine the winner, I don’t see how strings work with the function?

If you look in the game.js file, you’ll see this code that calls your updateScore function:

  const humanIsWinner = compareGuesses(currentHumanGuess, computerGuess, target)
  const winner = humanIsWinner ? 'human' : 'computer'

  // Update the correct score:
  updateScore(winner);

So, when your updateScore function is called, the parameter, winner is assigned to the argument passed to the function. That argument is one of two string literals. Either 'human' or 'computer'. Your function then tests the value that was passed to see which one it is, and updates the corresponding score variable. Does that help?

Got it! Thanks for explaining this!

1 Like