- What Is a Function?
- Creating a Function That Takes Arguments
- Creating a Function That Returns Data
Creating a Function That Returns Data
The last function variant we will look at is one that returns some data back to whatever called it. Here is what we want to do. We have our showDistance function, and we know that it looks as follows:
function showDistance(speed, time) { alert(speed * time); }
Instead of having our showDistance function calculate the distance and display it as an alert, we actually want to store that value for some future use. We want to do something like this:
var myDistance = showDistance(10, 5);
The myDistance variable will store the results of the calculation done by the showDistance function. There are just a few things you need to know about being able to do something like this.
The Return Keyword
The way you return data from a function is by using the return keyword. Let’s create a new function called getDistance that looks identical to showDistance with the only difference being what happens when the function runs to completion:
function getDistance(speed, time) { var distance = speed * time; return distance; }
Notice that we are still calculating the distance by multiplying speed and time. Instead of displaying an alert, we return the distance (as stored by the distance variable).
To call the getDistance function, you can just call it as part of initializing a variable:
var myDistance = showDistance(10, 5);
When the getDistance function gets called, it gets evaluated and returns a numerical value that then becomes assigned to the myDistance variable. That’s all there is to it.
Exiting the Function Early
Once your function hits the return keyword, it stops everything it is doing at that point, returns whatever value you specified to whatever called it, and exits:
function getDistance(speed, time) { var distance = speed * time; return distance; if (speed < 0) { distance *= -1; } }
Any code that exists after your return statement will not be reached, such as the following highlighted lines:
function getDistance(speed, time) { var distance = speed * time; return distance; if (speed < 0) { distance *= -1; }}
It will be as if that chunk of code never even existed. In practice, you will use the return statement to terminate a function after it has done what you wanted it to do. That function could return a value to the caller like you saw in the previous examples, or that function could simply exit:
function doSomething() { // do something return; }
Using the return keyword to return a value is optional. The return keyword can be used by itself as you see here to just exit the function.