If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

### Course: AP®︎/College Computer Science Principles>Unit 3

Lesson 7: Procedures

# 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));``````
📝 See similar code in: App Lab | Snap | Python
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.
📝 See similar code in: App Lab | Snap | Python

## 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;
}``````
📝 See similar code in: App Lab | Snap | Python

## 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)``````

## Want to join the conversation?

• what's the difference between returning a value and using println()? the exercises are a little confusing about this
• 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.
• 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?
• 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 variable `score` is a local variable within the function `calcScore`.

A local variable is only accessible inside the function where it is defined, meaning that if you attempted to access the variable `score` outside of the `calcScore` 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 of `score`, since the variable itself will be inaccessible once you exit the `calcScore` function. The returned value will be the same value that was held by the variable `score`, and that value can then be assigned to a variable (or just used as is) in the calling function.
• can you have multiple return statements in a function? or would the first return statement kill the following code?
• I have sort of a difficult question, why is school so stupid, they teach us to do math when we can easily do it on a calculator, why are they preparing us for the past?
• At this point, calculators are certainly easily accessible and powerful enough that they can do most math that the average person will use. However, they are simply tools. Without knowing how to use them properly, you risk misusing them. That is why it is important to understand how math works. For example, suppose you have a cake recipe that calls for 1/2 cup of sugar for the batter and 2/3 cup of sugar for the icing. You want to make two cakes and figure out how much sugar you need in total, so you type 1/2 + 2/3 * 2 into your calculator. Without knowing the order of operations, you might think this would give you the correct answer.

Furthermore, calculators are not perfect at math, even when using them correctly. I just used a calculator to simplify (sqrt(2))^2 and got back 2.0000000000000004 even though the answer is actually just 2. There is a lot of math that calculators cannot do at all.

Even if you don't need to use the math you learn in school, learning it still develops problem-solving skills which is generally important.
• what's the difference between returning a value and using println()? the exercises are a little confusing about this
• 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.
• function area(B,K,D) {
var areainsqm =(B*20*338.63)+(K*338.63)+(D*16.9315);
return areainsqm;
}
function DVrate (Market,gov) {
var umr=Market/338.63;
var dm = umr*0.6;
var dg = gov*0.4;
var tdv=dm+dg;
return tdv;
}
function DV(rate,area) {
var DV=rate*area;
return DV;
}
var area=area(0,2,1);
var rate = DVrate(100000,1000);
println("Total Distress value of land plots in NRs. "+DVrate(rate,area));
println("Total Market value of land plots in NRs. " + ?);

///where market value = umr * area
now question is can get market value without creating another function?? and how?
• You can define a global variable umr outside of the functions and set it as 0 by default. Then, erase the "var" in "var umr" inside the function "DVrate". As the function "DVrate" is called, umr will be populated publicly, so you can set "var market_value = umr*area;" at the end.