return

Ends a function and passes a value back to the place where the function was called.

On this page

Example

#
JavaScript
function discountPrice(price, percent) {
  if (percent <= 0) {
    return price
  }
  return price - (price * percent) / 100
}

console.log(discountPrice(200, 25))
console.log(discountPrice(200, 0))
Console
150
200

Definition and usage

#

The return statement immediately ends a function. The value written after it becomes the result of the call, which you can assign to a variable or pass along. Code after a return that actually ran never runs.

A function with no return, or with a bare return and no value, returns undefined. You can only return a single value, but it can be an array or an object, which you then unpack with destructuring.

Watch out for the newline. If the value starts only on the next line, JavaScript inserts a semicolon right after return, and the function returns undefined. Start a multi-line expression on the same line, for example with a parenthesis: return (.

Syntax

#
Syntax
return
return expression

More examples

#
Several values in one object
JavaScript
function stats(points) {
  const total = points.reduce((sum, p) => sum + p, 0)
  return { total, average: total / points.length }
}

const { total, average } = stats([80, 90, 100])
console.log(total, average)
Console
270 90
Pitfall: a new line after return
JavaScript
function getBadge() {
  return
  {
    name: 'First lesson'
  }
}

console.log(getBadge())
Console
undefined

JavaScript automatically inserts a semicolon after a bare return, so the object below it never gets returned. Keep the opening brace on the same line: return {.

Implicit return in an arrow function
JavaScript
const square = (n) => n * n
const noReturn = (n) => {
  n * n
}

console.log(square(4))
console.log(noReturn(4))
Console
16
undefined

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • An early return at the start of a function handles error cases and reduces nesting.
  • Make sure every path through a function returns the same kind of value. A function that sometimes returns a number and sometimes undefined easily breaks further calculations.

Related entries

#

Spotted a mistake or missing an example? Write to us.