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.

Every function returns a value. If you never write return, JavaScript sends back undefined.

Undefined return value

The return keyword ends the function immediately and passes a value to the caller. Nothing after it on that path runs.

Return an explicit value like this:

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

The caller decides what to do with the result. Logging inside the function is not the same as returning:

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 without braces:

const double = value => value * 2

Add braces and you need an explicit return. To implicitly return an object literal, wrap it in parentheses: value => ({ value }).

You can only return one value at a time. To send back related data, return an array or an object. I prefer objects when each field has a name callers should not mix up.

Using arrays:

const getDetails = () => [37, 'Flavio']

const [age, name] = getDetails()

Array destructuring depends on position. Swap the order in the array and you swap the values.

Destructuring using arrays

Using objects:

const getDetails = () => ({
  age: 37,
  name: 'Flavio'
})

const { name, age } = getDetails()

Property names matter here, not order.

Destructuring using objects

Pick one return shape and stick to it. If a function sometimes returns an object and sometimes nothing, every caller needs extra checks. Use null, a result wrapper, or throw when failure is exceptional.

Try this on your own: write a parser that returns { ok: true, value } or { ok: false, error }, then branch on ok instead of reading console output.

Call your parser with valid and invalid input in the console. The fulfilled branch should never depend on side effects from console.log.

Early return inside a function also stops execution, the same way return hands a value back at the end.

Lesson completed