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.

Main content

Procedures with return values

AP.CSP:
AAP‑3 (EU)
,
AAP‑3.A.7 (EK)
,
AAP‑3.A.8 (EK)
,
AAP‑3.C (LO)
,
AAP‑3.C.2 (EK)
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)

🙋🏽🙋🏻‍♀️🙋🏿‍♂️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?

  • leafers seedling style avatar for user Victoria
    what's the difference between returning a value and using println()? the exercises are a little confusing about this
    (9 votes)
    Default Khan Academy avatar avatar for user
    • starky ultimate style avatar for user KLaudano
      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)
  • leaf red style avatar for user layaz7717
    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)
    Default Khan Academy avatar avatar for user
    • leaf green style avatar for user Shane McGookey
      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.
      (6 votes)
  • leaf yellow style avatar for user Haylee Patch
    can you have multiple return statements in a function? or would the first return statement kill the following code?
    (2 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user mikaprad6956
    what's the difference between returning a value and using println()? the exercises are a little confusing about this
    (1 vote)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user NAVEED RIAZ
    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)
    Default Khan Academy avatar avatar for user
    • orange juice squid orange style avatar for user Evan
      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)
  • blobby green style avatar for user Ahmad MJ
    Does the return function also work for strings?
    (0 votes)
    Default Khan Academy avatar avatar for user