Why does console.log return a var string, but it's return is undefined?

I am working through the rock, paper, scissors assignment and the “get unstuck” video mentioned that when you console.log(var) (var = ‘string’) you will print the ‘string’ as expected. However, this will also print “undefined” if you do not request a return value as part of an else statement according to the tutorial.

I understand this as a “what” but not as a “why.”

Is this due to the data type? Would any and all possible printed characters return undefined if no return is requested in an else statement?

JavaScript will use undefined if a function/method doesn’t return a value. If you have a function that only returns a value sometimes, then the times that it doesn’t return a value, it will be undefined too.

Consider the following:

function testing(value) {
  if (value === 'yes') {
    return true;
  }
}

let returnedValue;

returnedValue = testing('yes');
console.log(returnedValue);
// prints: true

returnedValue = testing('nope');
console.log(returnedValue);
// prints: undefined

We have a function that returns a value only when the argument to the function equals yes. We didn’t include a return if the condition was not met, so whenever it doesn’t equal yes, JavaScript will use undefined.


In case I’m misunderstanding your question and you’re asking why returning a console.log() ends up being undefined, then:

return console.log(whatever);

would print the variable whatever to the console, but the method console.log() doesn’t return a value, so just like in the example I included earlier, JavaScript will use undefined.

2 Likes