Return Values

Functions can send a value back with return.

Syntaxfunction add(a, b) { return a + b; }

The return statement sends a value back to whoever called the function. The function stops running as soon as it hits return.

Using the result

Store the returned value in a variable, log it, or use it in an expression.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Return a calculated discount amount from a pricing function to store in the cart state.
  • Return early from a validation function with false as soon as one rule fails.
  • Return an object from a factory function to create new user records with computed defaults.

More examples

Return a computed value

Returns the discounted price so the caller can store or use the value.

Example · js
function discount(price, pct) {
  return price * (1 - pct);
}
const sale = discount(100, 0.2);
console.log(sale); // 80

Early return for validation

Returns false early when a guard condition fails, avoiding deeply nested if-else blocks.

Example · js
function validateAge(age) {
  if (typeof age !== "number") return false;
  if (age < 0 || age > 120) return false;
  return true;
}
console.log(validateAge(25));   // true
console.log(validateAge(-1));  // false

Return an object from a factory

Returns a new object from a factory function, using shorthand property names and defaults.

Example · js
function createUser(name, role = "viewer") {
  return { id: Date.now(), name, role, createdAt: new Date().toISOString() };
}
const admin = createUser("Alice", "admin");
console.log(admin.role); // "admin"

Discussion

  • Be the first to comment on this lesson.
Return Values — JavaScript | SoundsCode