JavaScript Reference ยท Statements and Declarations
The return statement
Reference for the JavaScript return statement: returning values, early exits, the automatic semicolon trap, constructors, async functions and generators.
The return statement ends the execution of the current function and hands a value back to the caller. If you leave out the value, or the function ends without reaching a return, the call evaluates to undefined.
return is valid only inside a function body (including arrow functions, methods and class bodies' methods). Using it at the top level of a classic script is a syntax error.
function double(n) { return n * 2; }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
return; return expression;
| Part | Description |
|---|---|
expression |
The value to return. If omitted, the function returns undefined. |
Return value: the call expression evaluates to whatever return produced.
Usage notes
- Automatic semicolon insertion. A line break directly after the word
returnends the statement, soreturnfollowed by a new line returnsundefinedand the next line becomes unreachable code. Start the returned expression on the same line asreturn, for example by opening a(,{or[there. - One value only. To return several values, return an array or an object and destructure it at the call site.
- Early returns flatten nested
ifblocks: check the unusual cases first and return, so the main path reads without indentation. - Arrow functions with an expression body return it implicitly:
n => n * 2. With a block body you need an explicitreturn. - Constructors. In a
newcall, returning an object replaces the created instance; returning a primitive is ignored. In a derived class constructor, returning anything but an object orundefinedthrows aTypeError. - Inside
try...finally. Areturninfinallyoverrides areturnorthrowfrom thetryorcatchblock, which is almost never what you want. - Async functions wrap the returned value in a promise. A thrown error becomes a rejected promise. Generators use
returnto finish the iterator and set the finalvaluewithdone: true. - Mixed returns. A function that sometimes returns a value and sometimes falls off the end is easy to misuse; return explicitly on every path.
Browser support
return works in every JavaScript engine.