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

Brian Martin
Brian Martin
3,773 Points

What is the point of the last example of using the return 5?

function noAlert() { return 5; alert(“This won’t appear”); }

noAlert(); alert(“This will appear!”);

Was this simply to show that if you run a return it will exit the program?

2 Answers

Chris Shaw
Chris Shaw
26,676 Points

Hi Brian,

This example isn't about the number 5, but about the return statement. In JavaScript return statements causes part of an script to stop processing whether it has a value or not. For example:

function noAlert() {
  alert("This won't appear");

In the above code I've removed the number 5 from the return statement, in JavaScript this is the same as saying return false;, however, we don't need a value as the browser assumes the end of the code is at the return statement. The example you've given is trying to teach you about how the flow of JavaScript works which is why the alert with This won’t appear doesn't execute as the return statement comes first.

Hope that helps.

So to my understanding, return is actually a way for the program to cycle to the top of the code, therefore in this code it won't run because it doesn't go through the alert() statement? Am I right?

Nick Field
Nick Field
17,091 Points

Tajul, the return statement ends the function by storing a string, number or boolean value defined. Afterward, any code after the return value (but before the closing curly brace of the function) is ignored.

So after the returns storing process, the program does not cycle to the top of the code, instead it continues to the next code. Later on in the program, when that function is called, the content stored in the return statement can be used.