- General Syntax
- Calling Functions
- Arguments
- Returning Values from Functions
- Scope of Variables
- Summary
- Q&A
- Workshop
- Exercises
Returning Values from Functions
Okay, now you know how to pass information to functions so that they can act on that information for you. But how can you get information back from your function? You won’t always want your functions to be limited to popping open a dialog box!
Luckily, there is a mechanism to collect data from a function call—the return value. Let’s see how it works:
function cube(x) { return x * x * x; }
Instead of using an alert() dialog within the function, as in the previous example, this time we prefixed our required result with the return keyword. To access this value from outside the function, we simply assign to a variable the value returned by the function:
var answer = cube(3);
The variable answer will now contain the value 27.