Rock, Paper, or Scissors

https://www.codecademy.com/paths/web-development/tracks/getting-started-with-javascript/modules/learn-javascript-functions/projects/rock-paper-scissors-javascript

SPOLER
**

Rock, Paper, or Scissors

Please help with the below. The code runs but when I log it, it gives me both the answers and an undefined. Why is this?

const getUserChoice = userInput => {

userInput= userInput.toLowerCase();

if (userInput== ‘rock’ ||userInput== ‘paper’ || userInput==‘scissors’) {

console.log(userInput);}

else {

console.log('Please insert the correct word');

};

};

console.log(getUserChoice(‘paper’));

**

When you’re logging the function call to the console, what you are doing is logging the return value. However, your function does not have any return, it’s a console.log() call, so it’s logging userInput to the console, and then your function is returning undefined, which is then being printed to the console.

2 Likes

You are not using a return statement.

In a function the program can perform many actions, but unless you use a return it does not do anything with the value it generates.

const addFive = number => {
  let a = number + 5;  
}

addFive(7)

If you run the above function, a variable is created equal to 12. However it does not do anything with this value and the variable will be deleted as soon as the function is done running.

If you try to log the same function:

console.log(addFive(7));

You will receive Undefined, because it was never specified what to log.
However if you use a return:

const addFive = number => {
  let a = number + 5;
  return a;
}

console.log(addFive(7));

Than the value of a will be returned from the function and 12 will be logged.


In your case you are attempting to log getUserChoice but you are not returning anything.
Hopefully this helps :slightly_smiling_face:

3 Likes

Thanks.
Makes sense. Solved it now. Used return inside the {} and console.log to print.

Many Thanks :pray:

1 Like

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