Is a console.log() the same thing as a return statement?

Question

Is a console.log() the same thing as a return statement?

Answer

No! console.log() will print whatever we pass into the parentheses to our development console, while a return statement will return a value to the function it’s associated with. To log the return value of a function call we can do something like this:

const myFunction () => {
  return 'Hello world!';
}
console.log(myFunction()); //will print 'Hello world!' to the development console because 'Hello world!' is the return value for the function

To log something from inside a function:

const anotherFunc () => {
  console.log('Yo world!'); //will print 'Yo world!' to the console when the function is called 
}
anotherFunc();

However if we use console.log() to log the return value of a function that contains a console.log() and no return statement:

const yetAnotherFunc () => {
  console.log('Hi world!'); //will print 'Hi world!' to the console when the function is called 
}
console.log(yetAnotherFunc()); //because no return value has been specified for the function, we'll also see `undefined` logged to the console after 'Hi world!' 

console.log is a utility function which helps us to print text to the standard output. return is a JavaScript keyword which stops execution of the closest outer enclosing function and provides the object or primitive value after the return keyword to the caller function or main program. If the there is no value or object after the return then undefined is used as the return value.

Every function returns a value whether the programmer explicitly writes a return statement in the function or not. If the there is no explicit return statement in a function then the function implicitly returns the value of undefined.

//explicit return statement function example1(){ return "hello world!" } const returnValue1=example1(); //the string "hello world" is assigned to the returnValue1 console.log(returnValue1); // will print 'hello world' //no return statement function example2(){ console.log("hello world!") } const returnValue2=example2(); // the value undefined is assigned to returnValue2 //and 'hello world!' is printed to the console console.log(typeof returnValue2); // will print "undefined" const returnValue3=console.log("hello world!"); //the value undefined is assigned to returnValue3 and //the text 'hello word!' is printed to the console console.log(returnValue2===returnValue3); // will print true console.log(typeof returnValue3); // will print "undefined"
1 Like