Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 156 ยท Functions

Return Values

Send results out of JavaScript functions with return. Learn early returns, returning objects and arrays, undefined by default, and pure functions.

Parameters carry data into a function. The return statement carries a result back out. It's what turns a function from "a block of code that does something" into "a question you can ask and get an answer to": what's the total, is this email valid, what's the next ID?

This lesson covers how return works, why functions without it give back undefined, how to use early returns to keep code flat, how to return several values at once, and a classic syntax trap with line breaks. Along the way you'll see why functions that return values are usually easier to work with than functions that print or change things.

How return works

return does two things at once:

  1. It ends the function immediately. Any code after it in the function doesn't run.
  2. It sends a value back to the place where the function was called. The call expression then evaluates to that value.
JS Returning a value

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Think of the call calculateTax(80, 0.2) as being replaced by its result, 16. That's why you can use it inside arithmetic, template literals or as an argument to another function.

return vs console.log

Beginners often mix these up, because both seem to "produce" a value. They are completely different:

  • console.log() shows a value to a human in the console. The program can't use what was printed.
  • return hands a value to the code that called the function, so the program can keep working with it.
JS Printing is not returning

Press Run (or Ctrl + Enter) to see the console output here.

No output.

As a rule, functions that compute something should return it, and let the caller decide whether to print it, store it or pass it on.

undefined by default

Every function call produces a value. If a function finishes without hitting a return, or uses return; with nothing after it, the call produces undefined:

JavaScript
function setup() {
  // no return statement
}

function stop() {
  return; // ends the function, returns undefined
}

console.log(setup()); // undefined
console.log(stop());  // undefined

That's fine for functions that just do something, like logging or updating the page. But if you expected a value and got undefined, check every path through the function: often one branch of an if forgot to return.

JS A missing return on one path

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Early returns

Because return exits the function immediately, you can use it to leave early once you already know the answer. You saw this idea as guard clauses in Conditionals. Early returns remove the need for else and keep the main logic at the left margin:

JS Early returns

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Early returns are also the cleanest way to leave a loop and the function in one step. Inside a for loop, return stops the loop and the function together, which is often clearer than break with a label:

JavaScript
function indexOfFirstNegative(numbers) {
  for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] < 0) return i;
  }
  return -1; // the loop finished without finding one
}

Notice the final return -1. A search function should always return something when it finds nothing, so callers don't get a surprise undefined. Common choices are -1 for positions and null for "no result".

Returning several values

A function can only return one value. When you need to send back more, wrap them in an object or an array, then unpack them on the other side with destructuring:

JS Returning an object or an array

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Prefer an object when there are more than two values or the order isn't obvious; the property names document themselves, and callers can take only what they need. An array is handy for a pair with a natural order, like [first, last] or [value, error].

Returning booleans directly

A comparison already produces true or false, so a function that answers a yes-or-no question rarely needs an if. Instead of this:

JavaScript
function isAdult(age) {
  if (age >= 18) {
    return true;
  } else {
    return false;
  }
}

return the comparison itself:

JavaScript
function isAdult(age) {
  return age >= 18;
}

The two versions behave identically, but the second says what it means in one line. The same works for combined conditions: return user.active && !user.banned;. If the expression might produce a truthy value that isn't a boolean, such as a string, and callers need a real true or false, wrap it in Boolean(...).

The line-break trap

JavaScript's automatic semicolon insertion (see Statements, Expressions and Syntax) has a famous rule for return: if a line break comes right after the return keyword, a semicolon is inserted there. Everything on the following lines is never reached.

JavaScript
function getConfig() {
  return
  {
    theme: "dark"
  };
}

console.log(getConfig()); // undefined!

JavaScript reads that as return; followed by an unreachable block. The fix is to start the value on the same line as return:

JavaScript
function getConfig() {
  return {
    theme: "dark",
  };
}

For long expressions that span several lines, open a parenthesis on the return line: return ( โ€ฆ );.

Returning functions

Functions are values, so a function can return another function. This is a powerful pattern you'll explore in Closures and Higher-Order Functions. Here's a taste:

JavaScript
function makeMultiplier(factor) {
  return function (n) {
    return n * factor;
  };
}

const triple = makeMultiplier(3);
triple(7); // 21

Pure functions

A function that computes its result only from its parameters and returns it, without changing anything outside itself, is called a pure function. Given the same inputs, it always returns the same output. calculateTax, shippingCostFixed and stats above are all pure.

Pure functions are the easiest to understand, test and reuse, because nothing they do is hidden. Of course, programs must eventually print, save or update the page; those are called side effects. A good habit is to keep the calculations in pure functions that return values, and put side effects in a few clearly named places.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a function return if it ends without a return statement?

    Every call produces a value. Without return (or with a bare return;), that value is undefined.
  2. 2. Given function f() { return 1; console.log("hi"); }, what happens when you call f()?

    return ends the function immediately, so the line after it never runs.
  3. 3. Why does this function return undefined? function g() { return followed by { ok: true }; on the next line

    Automatic semicolon insertion turns a return followed by a line break into return;. Start the value on the same line.
  4. 4. function show(n) { console.log(n * 2); } โ€” what is stored in const x = show(4);?

    show prints 8 but doesn't return anything, so the call evaluates to undefined.
  5. 5. What is the usual way to return two related values from a function?

    A function returns exactly one value. Wrap several values in an object or array and destructure them at the call site. return a, b uses the comma operator and returns only b.

Summary

  • return value ends the function and sends value back to the caller; the call expression evaluates to it.
  • console.log only shows a value; return lets the program use it.
  • Without return, or with a bare return;, a call produces undefined. Make sure every path of a value-producing function returns something.
  • Early returns handle special cases first and keep the main logic flat; return inside a loop exits both the loop and the function.
  • Return an object or array to send back several values, then destructure them.
  • Never put a line break right after return.
  • Pure functions, which compute from their inputs and return a result, are the easiest to test and reuse.

Next: Arrow Functions โ€” a shorter syntax for functions, with implicit returns.