{{jsSidebar("Statements")}}
return statement는 함수 실행을 종료하고, function을 호출한 caller에게 되돌려줄 값을 지정합니다.
Syntax
return [[expression]];
expression
- 만약 return 표현식에서 return을 생략할 경우에는 undefined가 반환 됩니다.
Description
함수에서 return statement가 호출될 경우, 함수는 더 이상 실행되지 않습니다. 만약 return 값이 주어진다면, 그 값이 function을 호출한 caller에 반환됩니다. return이 생략되는 경우에는 undefined가 반환됩니다. 아래의 return statement들은 모두 함수의 실행을 중단시킵니다.
return; return true; return false; return x; return x + y / 3;
Automatic Semicolon Insertion
return statement는 automatic semicolon insertion (ASI)의 영향을 받습니다. 줄바꿈으로는 return 키워드와 그 뒤에 나오는 표현식을 분리할 수 없습니다.
return a + b;
이것을 ASI로 변형시키면 다음과 같습니다 :
return; a + b;
이것을 실행시키면 console은 "return statement 이후에 도달할 수 없는 코드가 있습니다"라는 경고를 띄웁니다.
Starting with Gecko 40 {{geckoRelease(40)}}, a warning is shown in the console if unreachable code is found after a return statement.
Examples
return
아래의 함수는 x가 숫자일 때, x의 제곱을 반환합니다.
function square(x) { return x * x; }
Interrupt a function
함수는 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
Returning a function
Closures에 대해서도 더 알아보세요.
function magic(x) { return function calc(x) { return x * 42 }; } var answer = magic(); answer(1337); // 56154
Specifications
Specification | Status | Comment |
---|---|---|
{{SpecName('ES1')}} | {{Spec2('ES1')}} | Initial definition. |
{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}} | {{Spec2('ES5.1')}} | |
{{SpecName('ES6', '#sec-return-statement', 'Return statement')}} | {{Spec2('ES6')}} | |
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}} | {{Spec2('ESDraft')}} |
Browser compatibility
{{CompatibilityTable}}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} |