Why is there an "undefined" in my terminal?

Hi everyone​:grinning_face_with_smiling_eyes::wave:
can you tell me why is there an “undefined” in my terminal?

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

Hi, this has to do with how functions work. In this example, getUserChoice() is your function.

Functions always have return values. These values can have different types, (like integer, float, string, boolean, etc.). There is also a return value for functions that don’t return anything (void functions) which in javascript is undefined.

When you invoke a function, the function executes and will always return a value (if you don’t explicitly return one, it returns undefined, which is sometimes the desired outcome). So if your function is one of these void functions, you generally don’t want to console.log the invocation of the function… you simply invoke it.

myVoidFunction('Test'); // simply invoke, function will run
//as you defined it
console.log(myVoidFunction('Test')); // will always print 
//undefined to the console,
//along with whatever else your function does.
4 Likes