Introduction to Javascript

I don’t know what’s go wrong with my code. Here is my code:

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase(); 
  if (userInput === 'rock' || userInput === 'paper'||userInput === 'scissors') {return userInput;} else {console.log('Error Message');
  }
}

function getComputerChoice() {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) {console.log('The game was a tie'); 
  if (userChoice ==='rock') {
      if (computerChoice ==='scissors') {
      return 'user won' ;}else {return 'computer won';
    }
  }
    
  else if (userChoice ==='paper'){
    if (computerChoice ==='scissors') {
      return 'computer won';} else {return 'user won';}
    }
  }
  else if(userChoice ==='scissors'){
    if (computerChoice ==='rock') {
      return 'computer won';} else {return 'user won';
      }
    }
  }
determineWinner(getUserChoice(),getComputerChoice())
  

and here is the error:
home/ccuser/workspace/javascript_101_Unit_3/Unit_3/rockPaperScissors.js:2
userInput = userInput.toLowerCase();
^

TypeError: Cannot read property ‘toLowerCase’ of undefined
at getUserChoice (/home/ccuser/workspace/javascript_101_Unit_3/Unit_3/rockPaperScissors.js:2:24)
at Object. (/home/ccuser/workspace/javascript_101_Unit_3/Unit_3/rockPaperScissors.js:37:17)
at Module._compile (module.js:571:32)
at Object.Module._extensions…js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)

Whyyyy

Hello @nguynkiuchi189263598, the reason for this is that you are providing no input for the function. Here:

You provide no parameter, however, your function specifies one parameter:

In JS, unlike Python, instead of throwing an error when then parameters are not provided, the program turns those values into undefined.

1 Like

The error is pretty informative?

userInput is undefined. So how could that be?

Here:

determineWinner(getUserChoice(),getComputerChoice())

you call the getUserChoice function, but provide no argument for the parameter of the function

as a result, the parameter will get undefined value.

not only python, many languages would throw an error if you didn’t provide an argument for a mandatory parameter. JS is the odd one out here, and that is not a good thing :frowning:

1 Like