I’m learning about functions in JavaScript and I’m confused about the role of console.log()
and return.
function reusableFunction() {
console.log("Hi World");
}
reusableFunction();
I understand this function logs "Hi World" to the console. My questions are:
-
Why doesn’t this function need a
return
statement? I’ve seen other functions that are usedreturn
to send values back. Isconsole.log()
doing something similar? -
Why do we call the function with just
reusableFunction();
instead ofconsole.log(reusableFunction());
? When would I use the second way of calling the function?
I’m trying to understand the fundamental difference between displaying something in the console console.log()
and returning a value from a function. Can you explain this with clear examples and perhaps point me to some resources for further learning?
I tried reading Documents like MDN, JS, and Google Developer Docs. I even did a Google Search and kept getting the basics. It answered my question. I just simply want to know when you know to use a return
statement in your functions and when to console.log()
and then call the function, like this console.log(reusableFunction())
. I understand what console.log() is what the return statement is and the difference between both.
2
Answers
To answer #1:
The function itself simply does not return a value. That is an option for a function, to do some processing on some data and return the result, or a function can just do some processing and that’s it.
I think an analogy could be the difference between
Going to the post office to deliver a letter (no return value)
vs.
Going to the post office to pick up a package and do something with that package at home
#2
When you write Console.Log(reusableFunction()), you are simply combining these two items together. This would make more sense if ‘reusableFunction()’ were returning a result (as descibed in #1). In this case, it doesn’t really make sense because what you’re saying in essence is
But, like I mentioned, there is no returned value here. Now, you’re still calling the function, so the log line from within (console.log("Hi World");
) will execute as intended. But, this would be an unorthodox way of achieving this.
I hope this helps.
These are the detailed answers to both of your questions. I hope the answer will help you understand and clarify the concepts
Why doesn’t this function need a return statement?
Functions don’t necessarily need a return statement unless they’re supposed to produce a value. Here’s why:
console.log()
is used for outputting information to the console.(likeprinting to the console).
Why call the function with just
reusableFunction()
instead ofconsole.log(reusableFunction());
?reusableFunction()
calls the function and executes its body.console.log(reusableFunction())
would pass the function’s return value itself as an argument toconsole.log()
.Fundamental differences between displaying and returning values
console.log()
):