Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Creating Reusable Code with Functions Getting Information From a Function

Immanuel Jaeggi
Immanuel Jaeggi
5,164 Points

The return function is tough to understand.

I have looked at the videos and read some threads but the return function is unfortunately still unclear. Do you have some easy examples that could clear this up?

3 Answers

Steven Parker
Steven Parker
231,236 Points

First, "return" is not a function. It's something you use in a function, and it cannot be used outside of one.

When a "return" statement is encountered, the function immediately stops running and the execution flow returns to the point in the code where the function was called. When used by itself, this is the same as what happens when you reach the end of the function, but using "return" can cause it to end early (perhaps as a result of a test).

The other thing "return" can do is pass a value back to the caller. If you provide an expression after "return", that value will be seen by the calling code as the value of the function itself. For example:

function three() {
  return 3;
}

var num = three();  // "num" will now contain the value 3

Does that clear it up?

Immanuel Jaeggi
Immanuel Jaeggi
5,164 Points

Still a bit confused, esp. with why I would want a variable (here you named it as num) to hold three in it...

Steven Parker
Steven Parker
231,236 Points

I agree that is a trivial and not very useful assignment. I was just creating an example to show how calling the function gives you back the value that was used in the "return" statement.

I was confused as well but this answer clears it up for the most part.