return
statement
ends function execution and specifies a value to be returned to the function caller.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
return [[expression]];
expression
undefined
is returned instead.
当
return
statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument,
x
, where
x
is a number.
function square(x) {
return x * x;
}
var demo = square(3);
// demo will equal 9
If the value is omitted,
undefined
is returned instead.
The following return statements all break the function execution:
return; return true; return false; return x; return x + y / 3;
return
statement is affected by
automatic semicolon insertion (ASI)
. No line terminator is allowed between the
return
keyword and the expression.
return a + b;
is transformed by ASI into:
return; a + b;
The console will warn "unreachable code after return statement".
Starting with Firefox 40, a warning is shown in the console if unreachable code is found after a return statement.To avoid this problem (to prevent ASI), you could use parentheses:
return ( a + b );
A function immediately stops at the point where
return
被调用。
function counter() {
for (var count = 1; ; count++) { // infinite loop
console.log(count + 'A'); // until 5
if (count === 5) {
return;
}
console.log(count + 'B'); // until 4
}
console.log(count + 'C'); // never appears
}
counter();
// Output:
// 1A
// 1B
// 2A
// 2B
// 3A
// 3B
// 4A
// 4B
// 5A
See also the article about 闭包 .
function magic() {
return function calc(x) { return x * 42; };
}
var answer = magic();
answer(1337); // 56154
| 规范 |
|---|
|
ECMAScript (ECMA-262)
The definition of 'Return statement' in that specification. |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
return
|
Chrome 1 | Edge 12 | Firefox 1 | IE 3 | Opera 3 | Safari 1 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 | nodejs 0.1.100 |