It's a petty basic question which seems I don't fully understand,
What exactly is the use of return? In what cases should I use it?
What would the difference between these code samples be?
function fun(text) {
console.log(text);
};
function fun(text) {
return console.log(text);
};
To be clear: I know what return does, I just don't feel like I fully understand it's purpose and when should I use it
You should use return if your function needs to, well, return anything to its caller. In your example, it's not necessary to use return because console.log already does what you want it to do. But, if your function calculates something (for example a mathematical operation like adding the first two params it receives), it's logical it "returns" the result, like this:
function add(a, b) {
return a + b;
}
This way the function caller can use the result for whatever it's doing.
return is used to send a value back to where's it's called from. You use it if you want to return a value.
If you don't have a return statement, it's the same as return undefined. console.log returns undefined, so return console.log(text) returns undefined.
So, only return if you want to get a value from the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With