return
Ends a function and passes a value back to the place where the function was called.
Example
#function discountPrice(price, percent) {
if (percent <= 0) {
return price
}
return price - (price * percent) / 100
}
console.log(discountPrice(200, 25))
console.log(discountPrice(200, 0))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
#return
return expressionMore examples
#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)function getBadge() {
return
{
name: 'First lesson'
}
}
console.log(getBadge())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 {.
const square = (n) => n * n
const noReturn = (n) => {
n * n
}
console.log(square(4))
console.log(noReturn(4))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
returnat 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
undefinedeasily breaks further calculations.
Related entries
#- functionDeclares a named function: a block of code with parameters that you can call any number of times and that can return a result.
- () => {}An arrow function: a shorter function syntax, with no own this, and an implicit return for a single expression.
- if...elseRuns a block of code only when the condition is true, and otherwise an optional else block.
- DestructuringDestructuring pulls values out of arrays and objects straight into separate variables.
Spotted a mistake or missing an example? Write to us.