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 Functions Create Reusable Code with Functions Return a Value from a Function

Why use a Return Statement instead of Calling Function when running code?

I am confusing why use the return statement instead of call function when running code

2 Answers

Easiest way to answer this is to take the following example below. By using the return statement in the if block, will terminate the function once the alert("Hello Jake") has finished running. Once the function terminates it will move on to any of the other codes outside the function. If, however, you do not include a return statement, and just write alert("Hello Jake") without the return before it, the function would still work, BUT... It will not behave the same way. Because now, you have allowed the function to continue reading the code outside of the if block too. So, without the return statement, it will now pop up 2 alert boxes, (1) "Hello Jake", and then (2) "Please login as Jake", which doesn't make sense when you want only one part of the function to run successfully then immediately exit the function. So... This is where return comes useful.

NOW... Try using the code below in the console, and try it without the return statement too. You will immediately see the difference it makes.

function showName() {

    let askName = prompt("what is your name");
    if(askName === "Jake"){
      return  alert("Hello Jake");
    }

    alert("Please login as Jake");
}

showName();
Clayton Perszyk
MOD
Clayton Perszyk
Treehouse Moderator 48,850 Points

returning a value make the function more reusable and other parts of your code can use the returned value from the function.