LESSON 18

Return Values

Learning objective: Get results out of functions with return.

Understand

Functions can send a value back to the caller.

The return statement hands a result back and ends the function. Returned values can be stored in variables or used directly. A function without return gives back undefined.

Analogy: Returning is like a vending machine handing back the snack after you make a choice.

See It in Action

Returning a sum:

function add(a, b) {
  return a + b;
}
let total = add(2, 3); // 5
How it works: add returns the sum, which is stored in total for use elsewhere.

Try It Yourself

  1. Write a function that returns a value.
  2. Store the result in a variable.
  3. Use the result in another calculation.

Quick Quiz

What does a function without a return give back?

Challenge

Write a function that returns the larger of two numbers.

Success condition: Your function returns and you can store the correct result.