Function Results![[next]](../../img/ltp/arrow-next.gif)
In addition to performing actions, functions can also return values to wherever they were called, much like the mathematical operators we discussed in the chapter on variables.
When you're writing a function, return is the way to tell the computer what calling that function should evaluate to. The simplest case is code like this:
The function five takes no arguments and always returns 5. As soon as you "return" from a function, the function ends and no further code inside the function is executed.
Exercise: Dead code. Try modifying the above function to print something out after the return 5. What happens? Such code, which can never possibly get run, is called "dead code".
Here is a somewhat more useful function example.
|
1
2 3 4 5 6 7 8 9 function average(a, b) { return (a + b) / 2 } var x1 = average(4, 6) printp(x1) var x2 = average(4, average(5, 7)) printp(x2) |
Click to run the code. |
When x1 = average(4, 6) gets evaluated, the computer first evaluates average(4, 6) gets the value that's returned, and then puts that in x1.
But what about the statement, average(4, average(5, 7))? The diagram below explains how it is evaluated.
Writing functions is one of the key ways to make a large program easier to understand. By separating code that happens often into functions, you can also dramatically shorten a program.
Exercise: Life without functions. Rewrite the example above without using functions. See how useful functions are?
average.