Rock, Paper, or Scissors


#1

Hello,

i just startet coding and directly reached a Point where i din’t know how to solve my Problem.

var userInput = ‘Rock’;
unserInput = userInput.toLowerCase();

function getComputerChoice(){
var randomNumber = Math.floor(Math.random()*3);
switch (randomNumber) {
case 0:
return ‘rock’;
case 1:
return ‘paper’;
case 2:
return ‘scissors’;
}
}
function determineWinner(userChoice,computerChoice) {
if (userChoice === computerChoice) {
return ‘tie’;
}
if (userChoice === ‘rock’) {
if (computerChoice === ‘paper’){
return ‘Computer won!’;
} else {
return ‘You won!’;
}
}
if (userChoice === ‘paper’){
if(computerChoice === ‘scissors’){
} else {
return ‘You won!’;
}

}
if (userChoice === ‘scissors’){
if (computerChoice === ‘rock’){
return ‘Computer won!’;
} else {
return ‘you won!’;
}
}

}
function playGame() {
var userChoice = userInput;
var computerChoice = getComputerChoice();
console.log('You threw: ’ + userChoice);
console.log('The computer threw: ’ + getComputerChoice());
console.log(determineWinner(userChoice,computerChoice ));
}
playGame();

It prints me out what User and Computer threw:, but it doesn’t print me out who won. It just prints ‘undefined’

Thank you very much!


#2

Some operations in javascript result in undefined when what you asked for doesn’t make sense or isn’t there. If I were to debug this, I would find out which code is causing that to be written to screen, and then consider where the value came from.

For example, if 2 was printed, I might start commenting out console.log lines until it stops writing 2, then I would look at what argument was given to that console.log, maybe it was zebra - 5. If I expected zebra to be something other than 7 then I’d lookf for where it was last defined… and so on, until I found whatever wasn’t how it should have been.

Make sure to have a firm idea of everything that should happen in your code so that you have something to compare your observations to. Otherwise you wouldn’t know when something is wrong. That might involve reading the instructions some more until you’re convinced that you have the whole story of what’s supposed to happen.