The Return Keyword

The return keyword functions as you might suspect - it returns a value. The values it can return can be of any data type, and can be defined by custom statements or by core objects.

New scripters often become confused not by what is returned but where a value is returned to. The 2 golden rules of the return keyword are:

1. If the return keyword is used in a function body, a value is returned (or sent) back to where function is called.
2. If the return keyword is used in an event handler, a value is returned (or sent) to the browser.

1. Return Keyword used in a function body
function blue(){
var myColor = "blue"
return myColor
}
Since return keywords used in a function body return a value to the place the function is invoked, we'll invoke the function from an alert statement within an a tag, causing the value returned by blue() to be alerted.
<a href="javascript:alert( blue() )">call function</a>
I'll show you many more practical uses of the return keyword later within this tutorial.

2. Return Keyword used in an event handler

In this example, the return keyword is used within an onclick event handler located in an a tag. It is used to return a false value to the browser, essentially instructing the browser not to open the url.
<a href="../../default.php" onclick="return false">Try to Leave</a>
Since return keywords used within event handlers return a true or false value (boolean value) to the browser, they are generally used to interupt a natural browser behavior. In this example, the return false statement is interupting the browser's natural behavior of opening the URL contained in the href attribute's quotes. There is no convention as to when to use true or false - the various behaviors respond to true and false differently.

View the Source