Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use return?

Tags:

javascript

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

like image 685
ilyo Avatar asked Mar 28 '26 01:03

ilyo


2 Answers

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.

like image 182
cambraca Avatar answered Mar 29 '26 15:03

cambraca


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.

like image 29
Rocket Hazmat Avatar answered Mar 29 '26 13:03

Rocket Hazmat