This section provides a quick description on 'return' statements and return values. A tutorial example on how return values are passed back to calling expressions is provided.
JavaScript supports "return" statements to allow functions to return values back to calling expressions.
Here are some basic rules on the return value from a function.
If no return statement is used in a function, the calling expression will receive a special value: "undefined".
If the return value is a primitive value, the calling expression will receive a copy of the return value.
If the return value is an object reference, the calling expression will receive a copy of the object reference.
To help you understand different types of return values, I wrote this JavaScript tutorial example:
<html>
<!-- Return Values.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head><title>Return Values</title></head>
<body>
<pre>
<script type="text/javascript">
var resValue = valueReturn();
var resObject = objectReturn();
var resUndefined = noReturn();
document.write("\n\nAfter function calls:");
document.write("\n resValue = " + resValue);
document.write("\n resObject = " + resObject[0]);
document.write("\n resUndefined = " + resUndefined);
function valueReturn() {
document.write("\nInside valueReturn()");
var value = "String value";
return value;
}
function objectReturn() {
document.write("\nInside objectReturn()");
var object = new Array("Array object");
return object;
}
function noReturn() {
document.write("\nInside noReturn()");
}
</script>
</pre>
</body>
</html>
The output of this tutorial example shows no surprises:
Inside valueReturn()
Inside objectReturn()
Inside noReturn()
After function calls:
resValue = String value
resObject = Array object
resUndefined = undefined