Main content
AP®︎/College Computer Science Principles
Procedures with return values
Procedures can compute values for the rest of the program to use by sending back return values.
The need for return values
Our example procedures so far have all had side effects. That means they've affected their environment in some way, like the way that
println()
displays output on the screen.var score = (numCorrect/30) * 100;
println(score);
Many times, we don't want to immediately display a value to the screen. Instead, we want to remember the result of a calculation and use it in the future somehow. In that case, we tell the procedure to return a value to the code that called it.
In the JavaScript language, we can return values from a function by typing
return
followed by an expression to return.function calcScore(numCorrect) {
var score = (numCorrect/30) * 100;
return score;
}
Now that the function returns a value, we can use store its result in a variable, like this:
var sallyScore = calcScore(27);
var wilburScore = calcScore(24);
We can also directly call the function inside other functions:
println(calcScore(27));
println(calcScore(24));
Or we can call the function inside a larger expression:
println("Sally earned: " + calcScore(27));
println("Wilbur earned: " + calcScore(24));
Our call to
calcScore()
always returns a value, so we can use it anywhere that expects a value. That's a lot of places!In fact, we've already been using a number of built-in procedures that return values, like for math and string operations:
var maxNum = Math.max(33, 100);
var firstName = "Harry Potter".substr(0, 5);
var yell = "im hungry".toUpperCase();`
Now, we know how to define our own procedures with return values, and we can build up a library of useful procedures that compute values for our program's needs.
✏️ The program below calculates how many "me" would need to be stacked to reach certain heights, like the moon or the statue of liberty. Change it to calculate the number of "you" instead and add another structure, like Mt. Everest or the sun.
Watch out for early returns
The following bit of code has a bug:
function calcLineSlope(x1, y1, x2, y2) {
var yDiff = y2 - y1;
var xDiff = x2 - x1;
return slope;
var slope = yDiff / xDiff;
}
Do you see what it is? Here's a hint: whenever the computer executes a
return
statement, it exits the function immediately. Once it's exited the function, it won't execute any more code in the function.That means that the computer only executes this code:
function calcLineSlope(x1, y1, x2, y2) {
var yDiff = y2 - y1;
var xDiff = x2 - x1;
return slope;
}
It never gets to the line that calculates the slope, so it returns an undefined value to whoever calls it. The line of code after it is "dead code", code that will never ever be executed.
In the correct version of the code, the return statement is the very last line in the function:
function calcLineSlope(x1, y1, x2, y2) {
var yDiff = y2 - y1;
var xDiff = x2 - x1;
var slope = yDiff / xDiff;
return slope;
}
Return values in pseudocode
This pseudocode represents a procedure that takes two parameters named
parameter1
and parameter2
, contains programming instructions, and then returns the value of expression
.PROCEDURE name (parameter1, parameter2)
{
<instructions>
RETURN (expression)
}
Here's pseudocode for the
calcLineSlope
procedure and calls:PROCEDURE calcLineSlope (x1, y1, x2, y2)
{
yDiff ← y2 - y1
xDiff ← x2 - x1
slope ← yDiff / xDiff
RETURN slope
}
slope1 ← calcLineSlope(1, 2, 4, 5)
slope2 ← calcLineSlope(0, -1, 3, 10)
🙋🏽🙋🏻♀️🙋🏿♂️Do you have any questions about this topic? We'd love to answer— just ask in the questions area below!
Want to join the conversation?
- what's the difference between returning a value and using println()? the exercises are a little confusing about this(9 votes)
- When you return a value, the value is being passed to whatever called the function, allowing the returned value to be used elsewhere in the program. Using the command println simply displays the value on the screen for the user to see.(15 votes)
- Hello,
I'm looking at the second code example. I was just wondering why we need a return statement if we already have score stored as a variable. What's the purpose of the return statement? Why can't we just call the variable later on when we need to manipulate it or use println() for when we have to print it?
Furthermore, how does the computer known which value it has to return if we are using the procedure multiple times?(5 votes)- You'll want to look into variable scope - that would help to answer your questions. I'll give a short explanation that will hopefully lead you in the right direction...
Each variable that you declare has a scope, and that scope is dependent upon the language's conventions. JavaScript uses lexical scoping, and in this instance the variablescore
is a local variable within the functioncalcScore
.
A local variable is only accessible inside the function where it is defined, meaning that if you attempted to access the variablescore
outside of thecalcScore
function, you would encounter an error. A local variable differs from a global variable, which is defined outside of all functions. A global variable is accessible to all functions, but we aren't working with a global variable here.
Given this, you'll want to return the value ofscore
, since the variable itself will be inaccessible once you exit thecalcScore
function. The returned value will be the same value that was held by the variablescore
, and that value can then be assigned to a variable (or just used as is) in the calling function.(6 votes)
- can you have multiple return statements in a function? or would the first return statement kill the following code?(2 votes)
- From the author:You can have multiple return statements in a function. However, it only makes sense to have multiple return statements if there are multiple paths for the code. For example, your function might have an if statement, with different return statements for each of the if/else if/else blocks. More on if statements here:
https://www.khanacademy.org/computing/ap-computer-science-principles/programming-101/boolean-logic/a/conditionals-with-if-else-and-booleans
If the code inside the function can only go down one path, then there should only be a single return statement, at the very end of the function.(7 votes)
- what's the difference between returning a value and using println()? the exercises are a little confusing about this(1 vote)
- The function "println" displays the value for the user to see. Returning a value allows the value to be used outside of the function that calculated it.(1 vote)
- For the exam, if a numerical problem like finding ceiling = numBalloons/balloonsInBag is to be answered, will v have to convert pseudo code into JS and answer or just do the calculations in rough and answer?(0 votes)
- During the exam, you won't have the chance to covert the pseudocode to any other programming language. You'll need to work through the code in your head or on paper. Don't worry, they won't have you doing complicated math, mostly just logic type stuff.
However, due to COVID-19, there won't be a multiple choice exam for 2020. You should reach out to your teacher or go to the College Board website for more info.
Hope this helps! (:(1 vote)
- Does the return function also work for strings?(0 votes)
- Yes, the return value can be of any type.(0 votes)