When to use "return"?

Hi everyone,

There is an example in the lesson:

> const sleepTimer = (alarm) => {
>   console.log('My alarm is set for: ' + alarm);
> }
>  
> sleepTimer('8:30AM');

Sometimes it will show “undefined” when I didn’t type return in the function. But in this example, there is no return, but the result went well. I am confused about when to use “return” and when there is no need to use it.

Could anyone explain to me with more examples? Thank you!

return literally means what is say: returning/handing back data to caller/function call

lets say we have a function getSum:

const getSum = (a, b) => {
   const result = a + b;
}

result now has a local scope, the variable can only be accessed inside the function. However, if we use return:

const getSum = (a, b) => {
   const result = a + b;
   return result;
}

const theSum = getSum(5, 4);

we now have the variable outside the function:

console.log(theSum);

of course, you can also log the returned result directly:

console.log( getSum(5, 4));

but then we can no longer is it later if we need it

also, the intermediate variable within the function itself is redundant:

const getSum = (a, b) => {
   return a + b;
}

this function might not be very exciting, do much, but I hope you can imaging why return might be useful if our function does more complex logic

Thank you for your clear explaination. Could I know why there is no “return” in the example I gave above? Thank you

In the example above, you are simply printing the message; you aren’t giving any data back to the program. If you wanted to use the result of calling the sleepTimer function in a variable, then you would have to use return:

const sleepTimer = (alarm) => {
return "My alarm is set for:" + alarm;
}

let someVar = sleepTimer("8:30AM");
//now you can use this value anywhere else in your program.

Thank you for your answer. I understand now! :grinning:

1 Like