Why do I get undefined

const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
if (userInput === ‘rock’ || userInput === ‘paper’ || userInput=== ‘scissors’) {
return userInput;
}
else {
console.log(‘Error!’);
}
}
console.log(getUserChoice(‘scissor’));

\Error!
undefined

Invoking a function means that the code in the function gets executed. Functions can be broadly categorized into 2 camps: those that return data and those that don’t.

Whenever you’re logging a function invocation, be mindful that the function must the kind that returns something for this to be effective.

If your function doesn’t return something, it’s enough to invoke the function alone (and put the log inside the function to see what it gets up to).

In essence, your code above:

  • logs the invocation of a function
  • looks for a return value
  • but because it’s in a conditional, it seems like it’s not reached
  • it will continue looking for a return value, but since it can’t find one, the return value is undefined.
  • hence, it logs the return: undefined.
1 Like

Thank you @toastedpitabread for the explanation. This helps!