JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 5: Functions and Reusable LogicLesson 23 of 150About 40 minutes

Lesson 23: Return values

01Opening question

A function prints a total, but the checkout needs that total to add shipping. How does a function hand a value back?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

return sends a value back to the place the function was called. The call addTax(50) becomes 60.

function addTax(amount) {
  return amount * 1.2;
}
const withTax = addTax(50);
console.log(withTax + 5);

03Objective and prerequisites

Learning objective: Return values from functions, use the result in expressions, explain that return ends the function, and choose between printing and returning.

You need: Lesson 22: Parameters and arguments

Skills practised: Functions, Return values.

04Explanation

return value; sends a value back to the caller. The call expression, such as addTax(50), is replaced by that value, so you can store it, print it or use it in a calculation.

return also stops the function. Lines after a return in the same path never run.

A function without return (or with return; alone) gives back undefined.

Printing and returning are different. console.log shows a value to a person; return gives a value to the program. Reusable calculation functions should return, and let the caller decide whether to print.

05Definitions

Return value
The value a function sends back to its caller.
return statement
Ends the function and gives back a value.
Side effect
A change outside the function, such as printing or modifying a global.
Pure function
A function whose result depends only on its inputs and that has no side effects.
Early return
Returning at the start of a function when input is invalid or a simple case applies.

Open the full glossary

06Visual learning object

Function call stack and return-value tracer. Watch each call push a frame, and each return replace the call with its value.

Loading the interactive object…

Open the full Function return-value visualizer page with its guided experiment.

07Examples

ex-023-01Use the returned value Browser-executable JavaScript

The call becomes its return value.

function subtotal(qty, price) {
  return qty * price;
}
const a = subtotal(2, 6);
const b = subtotal(1, 9);
console.log(a, b, a + b);
Sample input
None
Expected output
12 9 21
Common mistake
Printing inside the function, then getting undefined when using the call in a sum.
Try this
Add a third line and a grand total.
Source
examples/ex-023-01-return-and-use.js (repository pending publication)

ex-023-02Printing is not returning Browser-executable JavaScript

A function that only logs gives back undefined.

function logDouble(n) {
  console.log(n * 2);
}
function double(n) {
  return n * 2;
}
const x = logDouble(4);
const y = double(4);
console.log(x, y);
Sample input
None
Expected output
8 undefined 8
Common mistake
Expecting x to be 8 because 8 was printed.
Try this
Use double(double(3)) and predict the result.
Source
examples/ex-023-02-print-vs-return.js (repository pending publication)

ex-023-03Early return Browser-executable JavaScript

return stops the function, so later lines do not run.

function shippingFor(total) {
  if (total >= 50) return 0;
  if (total >= 20) return 4.99;
  return 9.99;
}
console.log(shippingFor(75), shippingFor(30), shippingFor(10));
Sample input
None
Expected output
0 4.99 9.99
Common mistake
Adding else after each return, which is unnecessary.
Try this
Add a rule: totals of 0 return 0.
Source
examples/ex-023-03-early-return.js (repository pending publication)

ex-023-04Returning several values Browser-executable JavaScript

An object groups related results into one return value.

function orderSummary(subtotal, taxRate) {
  const tax = subtotal * taxRate;
  return { subtotal, tax, total: subtotal + tax };
}
const s = orderSummary(40, 0.05);
console.log(s.subtotal, s.tax, s.total);
Sample input
None
Expected output
40 2 42
Common mistake
Writing two return statements and expecting both values.
Try this
Add a shipping property to the returned object.
Source
examples/ex-023-04-return-object.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Return, do not log

Change a printing function into a returning one.

function areaOf(width, height) {
  console.log(width * height);
}
const total = areaOf(3, 4) + areaOf(2, 5);
console.log("Total area:", total);

Grade letter

Write a function with early returns.

function gradeFor(score) {
  // TODO: return "A" for 90+, "B" for 80+, "C" for 70+, otherwise "F"
}
console.log(gradeFor(95), gradeFor(84), gradeFor(70), gradeFor(52));

Invoice summary

Return an object from a pure function and print it outside.

const lines = [
  { qty: 2, price: 15 },
  { qty: 1, price: 30 },
  { qty: 4, price: 2.5 }
];

09Prediction

Commit to an answer first, then run the real code to compare.

function f(n) {
  if (n > 5) return "big";
  console.log("checking");
  return "small";
}
console.log(f(9));
console.log(f(2));

What lines are printed?

10Debugging investigation

The checkout total is NaN

The checkout prints the subtotal correctly, then shows Pay: $NaN.

function subtotal(prices) {
  let sum = 0;
  for (const p of prices) sum += p;
  console.log("Subtotal:", sum);
}
const SHIPPING = 5;
const pay = subtotal([12, 8]) + SHIPPING;
console.log(`Pay: $${pay}`);

More cases in the Debugging Detective Laboratory

11Practical scenario

Reusable price logic

The same total function feeds the cart page, the receipt and the analytics report. Because it returns a number instead of printing, each part of the app can use the value its own way.

function cartTotal(prices) {
  let t = 0;
  for (const p of prices) t += p;
  return t;
}
console.log(`Pay $${cartTotal([3, 4])}`);

12Knowledge check

1. What is printed?

function f() { 2 + 3; }
console.log(f());
  • 5
  • undefined
  • NaN
  • An error

2. What happens to code after return in the same path?

  • It runs last
  • It never runs
  • It runs first
  • It causes an error

3. What is printed?

const double = function (n) { return n * 2; };
console.log(double(double(4)));
  • 8
  • 16
  • 4
  • undefined

4. Why does this return undefined?

function total() {
  return
    10 + 5;
}
  • return cannot return numbers
  • A line break after return
  • total is not defined
  • The function is not called

5. Which is a pure function?

  • One that prints a receipt
  • One that returns a + b and changes nothing else
  • One that edits a global
  • One that reads the clock

6. A tax function will be used by several pages. What should it do?

  • Print the tax
  • Return the tax
  • Store it in a global
  • Show an alert

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Return, do not log: Prints only the total; areaOf returns
  • Grade letter: Prints A B C F; Boundaries
  • Invoice summary: Prints the summary; Returns the totals; No console.log inside summarise
  • ex-023-01: output matches the documented expected output
  • ex-023-02: output matches the documented expected output
  • ex-023-03: output matches the documented expected output
  • ex-023-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-01-foundations/module-05-functions-and-reusable-logic/lesson-023-return-values/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • return gives a value back to the caller and ends the function.
  • No return means undefined.
  • Print for people; return for programs.
  • Return objects for several values and use early returns for simple cases.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation Return values
Context: I know parameters.
Task: Explain return versus console.log with a checkout example.
Constraints: Beginner level.
Expected behaviour: I can say when to return.
Testing: Give me three functions to convert.
Code prediction Return drill
Context: I understand return.
Task: Give me six programs with early returns and missing returns and ask what is printed.
Constraints: Wait for answers.
Expected behaviour: Each has one answer.
Testing: Explain with the call stack.
Debugging NaN totals
Context: My total is NaN when I add two function results.
Task: Help me find why with questions.
Constraints: No direct answer.
Expected behaviour: I fix it myself.
Testing: Suggest a quick check of the return value.
Exercise generation Pure functions
Context: I finished the invoice summary.
Task: Create three pure-function exercises with exact tests.
Constraints: Fictional data.
Expected behaviour: Each returns a value or object.
Testing: Include expected outputs.
Code review Side effects
Context: My calculation functions print and update globals.
Task: Show me how to make them pure.
Constraints: Keep behaviour identical.
Expected behaviour: Printing happens in one place.
Testing: Explain the benefits.