Help understanding this function's "undefined" return

In the function below the return is the randomNumber and undefined. I do not understand why is undefined. Anybody can help me with this?
Thank you.

https://www.codecademy.com/workspaces/630b75313a5e6d3f6f8cf248

It’s because you are calling console.log() while passing in a function that also calls console.log(). You can just put getComputerChoice(); and it will print the result for you without the undefined.

If you want to dig deeper, getComputerChoice() does not return anything, which is why the undefined gets printed. Essentially, you are trying to print the resulting value of a function that doesn’t produce a resulting value.

Now what if you did the following instead? Now you are returning a string value from the function, so you will not get undefined anymore.

const getComputerChoice = () => {
  const randomNumber = Math.floor(Math.random() * 3);
  if (randomNumber === 0) {
    return 'rock';
  } else if (randomNumber === 1) {
    return 'paper';
  } else if (randomNumber === 2) {
    return 'scissors';
  } 
};

console.log(getComputerChoice())
1 Like

I understand now.
Thank you very much

1 Like