Functions and scope

JavaScript Return Values

Learn how return values work in JavaScript, why every function returns undefined by default, and how the return keyword ends a function and hands back a value.

8 minute lesson

~~~

Every function returns a value, which by default is undefined.

Undefined return value

return immediately ends that function call and gives a value to its caller. Code after it in the same path does not run.

If you pass a value, that value is returned as the result of the function:

const dosomething = () => {
  return 'test'
}
const result = dosomething() // result === 'test'

The caller decides what to do with the value: store it, pass it, render it, or ignore it. Logging a result is not the same as returning it:

function add(a, b) {
  console.log(a + b)
}

const total = add(2, 3) // logs 5, but total is undefined

Arrow functions can return an expression implicitly:

const double = value => value * 2

Braces change that rule; with a block body, write return explicitly. To implicitly return an object literal, wrap it in parentheses: value => ({ value }).

You can only return one value.

Group related values in an object or array. Prefer an object when each field has a meaning and callers should not depend on position:

Using arrays:

Destructuring using arrays

Using objects:

Destructuring using objects

Return shapes are part of a function’s contract. A function that sometimes returns an object and sometimes nothing forces every caller to handle both cases. Make absence deliberate with null, a result object, or a thrown error according to the API’s needs.

Try it: write a parser that returns { ok: true, value } or { ok: false, error }, then handle both results without inspecting console output.

Lesson completed